akcza
akcza

Reputation: 43

Java casting and polymorphism

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".

Upvotes: 1

Views: 543

Answers (4)

kirti
kirti

Reputation: 4609

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();

Upvotes: 1

Abhi Urs
Abhi Urs

Reputation: 95

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
}

}

Upvotes: 0

TheLostMind
TheLostMind

Reputation: 36304

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.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533520

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()

Upvotes: 4

Related Questions