-1

I have these two classes and I want to know why the output is A, B, and B.xxx. Can someone explain why it is not A.xxx when it is casted?

Here are my two classes and the main method:

public abstract class A {
    public A() {
        System.out.println("A");
    }

    public void xxx() {
        System.out.println("A.xxx");
    }

    abstract void yyy();
}

public class B extends A {
    public B() {
        System.out.println("B");
    }

    public void xxx() {
        System.out.println("B.xxx");
    }

    public void yyy() {
        System.out.println("B.yyy");
    }
}

public class ClassRunner {
    public static void main(String[] args) {
        B b2 = new B();
        ((A)b2) .xxx();    
    }
}
clemens
  • 16,716
  • 11
  • 50
  • 65

1 Answers1

0

So when you have inheritance...a variable initialization of the form

A my_A = new B()

where B extends A...is called disguising. You are disguising an instance of B as an object of A. And the rule of thumb is that the class on the left side of the equals sign (A) defines which methods you are allowed to call on your object. Since class A has the ".xxx()" method, we are allowed to use it. On the other hand, the class on the right hand side of the equals sign defines the actual version of the .xxx() method that we use. Since class B is on the right side, we use B's version of .xxx(). If B does not have a .xxx(), then it defaults to using A's version of it.

Solace
  • 2,161
  • 1
  • 16
  • 33
  • So since on both sides of the equal side are B, you are saying it will use the method in the B class regardless of the cast? – Shyam Patel Nov 29 '17 at 02:42
  • When you casted b2 to an A with ( (A)b2 ), the left side becomes an A, but since the underlying object is still an instance of B, it will use B's version of xxx() – Solace Nov 29 '17 at 02:44