+ 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); } }

16th Aug 2019, 10:04 PM
Juan Debenedetti
Juan Debenedetti - avatar
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?
16th Aug 2019, 11:40 PM
Juan Debenedetti
Juan Debenedetti - avatar
+ 2
~ swim ~ Yes, my fault. I deleted it. A a = new B(); //upcasting B b = (B) a; //downcasting
17th Aug 2019, 10:40 AM
Denise Roßberg
Denise Roßberg - avatar
+ 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
17th Aug 2019, 12:02 AM
Denise Roßberg
Denise Roßberg - avatar