+ 1
Why does this problem print 10?
public class A{ int x = 10; } public class B extends A{ int x = 20; } public class Main{ public static void main(String[] args){ A a = new B(); System.out.println(a.x); } }
3 Réponses
+ 2
~ swim ~
But what is the point of creating an object of type B when I am actually creating an instance of A although at no time do I create an object of type A?
This is polymorphism?
+ 2
~ swim ~
Yes, my fault. I deleted it.
A a = new B(); //upcasting
B b = (B) a; //downcasting
+ 1
Juan Debenedetti
Inside an inheritance hierarchy it is possible to cast an object.
A a = new B() is called upcasting. Because class B is a child class of A. And every child class is an instance of the parent class (when you create an object B -> constructor of A and B is called)
Printing a.x shows you 10 instead of 20 because your object is from type A not B.
The parent class of all classes is the Object class.
Object o = new A();
-> this would be an object from type Object