The printout is: Fruit Apple Golden Golden
I want to know why the object c.make()
invokes a method in class Golden
instead of class Apple
.Because I think that c is the object of class Apple, where is my mistake? Thanks for your consideration.
public class Fruit {
public Fruit(){
System.out.println("Fruit");
}
public void make(){
System.out.println("Fruit");
}
}
class Apple extends Fruit{
public Apple(){
System.out.println("Apple");
}
public void make(){
System.out.println("Apple");
}
}
class Golden extends Apple{
public Golden(){
System.out.println("Golden");
}
public void make(){
System.out.println("Golden");
}
}
public class tet {
public static void main(String[] args){
Fruit b = new Golden();//Fruit Apple Golden
Apple c = (Apple)b;
c.make();
}
}
No, c
is the same as b
. In fact they point to the same exact object, which is of type Golden
. You just choose to "view" the object through an Apple
reference, but the actual type doesn't change.