Please see the code demo as the following and I have misunderstanding of inheritanceHierarchy problem about casting. Just the example shows below, the correct result is Baz 1 Foo 3. I do not why we get this answer.
What I think is determine the compile-time type of e which is of type Object. No Compile time error occurs when cast Foo because casting up and casting down are both ok. Also Foo type have .one() method. Then considering runtime type that Object e = new Baz(); and Baz type can be casted to Type Foo because casting above the object's runtime type is ok. So that no runtime occurs and determine the output. I think that casting means make one object type turn into another one, so e is Foo type now and just check method one in Foo type. I get "Foo1". And it is wrong. Can anyone help me to solve this problem? Thank you!
public class inheritanceHierarchy
public static void main(String[] args) {
class Foo {
public void one() {
System.out.println("Foo 1");
}
public void three() {
System.out.println("Foo 3");
}
}
class Baz extends Foo {
public void one() {
System.out.println("Baz 1");
super.three();
}
public void two() {
System.out.println("Baz 2");
}
}
Object e = new Baz();
((Foo) e).one();
}
}
I think that casting means make one object type turn into another one, so e is Foo type now and just check method one in Foo type.
No. Casting doesn't change the type of the object at all. It only gives you an expression of the target type. So for example:
String x = "foo";
Object y = x;
String z = (String) y;
Here we have three references, all to the same object. The object doesn't change its type, and the values of the variables aren't objects - they're just references. It's crucial that you understand that.
So in your case, the only object is still an instance of Baz
, so when you call one()
you're still ending up calling the override within Baz
.
See more on this question at Stackoverflow