Inheritance in Java is a simple explanation

So, I have this:

public class A {

    public int a = 0;
    public void m(){
        System.out.println("A"+a);
    }
}

And this:

public class B extends A {

    public int a = 5 ;
    public void m (){
        System.out.println("B"+a);
    }
    public static void main(String[] args) {
        A oa = new A();
        B ob = new B();
        A oab = ob;
        oa.m();
        ob.m();
        oab.m();

        System.out.println("AA"+oa.a);
        System.out.println("BB"+ob.a);
        System.out.println("AB"+oab.a);
    }
}

Conclusion:

A0
B5
B5
AA0
BB5
AB0

I do not understand why the output is oab.m (); B5 instead of A0 . Can someone explain this to me?

0
source share
7 answers

That is the whole point of polymorphism. The specific type oabis equal B(since the object was created using new B()). Therefore, the method is called B.m().

Check out the Animal example at http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29 to see why it is useful. When you have an animal, and this animal is a Cat, you expect him to say "Meow!" when you speak.

+9
source
B ob = new B();
A oab = ob;

Similarly

A oab=new B();

I don't understand why oab.m(); output is B5 instead of A0

B A, m() B version of m().

+1
A oa = new A();
B ob = new B();
A oab = ob;

ob B. A, A B. B , , A m() . , out out B5

0

, .

 B ob = new B();
 A oab = ob;

oab A, B, ob, oab.m() m() B

0

Java - (). , ( ), . oab.m(); JVM () aob ( B) . oab.m(); B5.

, , . , oab.a 0 5.

0

, :

public class C extends A {

public int a = 7 ;
public void m (){
    System.out.println("C"+a);
}

, ...

C oc = new C();
A oac = oc;
oac.m();

... , C.

, B - A, C - A, , A, , .

:

// Get an instance of B or C, but you don't
// care which - could be either:
A someVersionOfA = getAnInstanceOfA(); 

// This works no matter if you've got an instance
// of B or C, but the result should vary accordingly:
someVersionOfA.m();

, A "Animal", B "cat" C "". m() " ", m() "Meow" "Woof!". getAnInstanceOfA().

0

You have just copied B's internal address and replaced it.

B inherits from A, so no compilation problem.

Finally, the link to A is destroyed, now it is a copy of the link to B

0
source

All Articles