1
public class A {
  public void x()
  {
    System.out.println("A");
  }
}

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

B b = new B();
A a = (A) b;
a.x();

This code prints "B". Could you tell me why? I thought that it would print "A".

2
  • Because you're calling the method on an object of type B Commented Jan 30, 2015 at 10:38
  • You already used the term polymorphism in your headline. Google it and you will find tons of tutorials on that topic. Commented Jan 30, 2015 at 10:40

4 Answers 4

4

B b is a reference to the new object you created new B()

When you cast the reference from a B to an A, the object is unaltered and untouched and it does exactly the same thing when you call the overridden method x()

Sign up to request clarification or add additional context in comments.

Comments

1

Just add this one line in your code and check : System.out.println(a.getClass()); . It prints class B .

    B b = new B();
    A a = (A) b;
    a.x();
    System.out.println(a.getClass()); // prints Class B

So basically, even if you cast b to (A), the method being called will be of B. That's polymorphism. Look at the object, provided the reference meets the contract.

Comments

1

Thats because :

This will create a new object of class B with object reference b

B b = new B();

In this u a is the object reference of Class A ,and you are using a=b so it means that a will refer to the same object that b is reffering that is the object of Class B so thats why it goes into the method of Class B and prints B

A a = (A) b;
a.x();

Comments

0

while casting the object, we have following posibilities.. 1.parent=child 2. child=(child)Parent

public class C {

public static void main(String[] args) {

    B b = new B(); // b is child
    TestPoly t= new TestPoly(); // t is parent
    t=(TestPoly)b;//parent=(parent)child   i.e parent=child
    t.x(); // return B


     b=(B)t; //child=(child)parent i.e  b=t
     b.x(); // return B (because your calling child.x())


     B b1 = new B();//child
     TestPoly a = (TestPoly) b1;//p=(p)c; ie= p=child
     a.x(); //return B
}

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.