1

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



}
  • Because even if you cast it to `Apple`, it still is an object of type `Golden`, and since the `make` method is overridden the one inside the `Golden` class gets called. – BackSlash Apr 05 '17 at 13:02
  • What happens in the stack and heap when (Apple)b shows up? Nothing happens, including the direction of b pointing to the heap? – APRIL Paxton Apr 05 '17 at 13:21
  • To be very Simple **Rule 1** In the heap `object` of that class is created with which you use `new` operator. **Rule 2** Reference of the class with which you used `new` and all the `classes and interfaces` in the higher hierarchy of that class is only allowed to refer the Object created. *Note* Referring a Dog by Cat is invalid and referring a dog by animal doesn't take away the capability of barking, its there as its a **dog**. :) – nits.kk Apr 05 '17 at 14:00

1 Answers1

2

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.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • What happens in the stack and heap when` (Apple)b` shows up? Nothing happens, including the direction of b pointing to the heap? – APRIL Paxton Apr 05 '17 at 13:22
  • You can use `javap` to see the bytecodes generated, but there's nothing very special about using a superclass reference to point to a subclass. Just like you'd write `List<> list = new ArrayList<>();` and you wouldn't expect that you'd suddenly have an instance of the interface `List`. – Kayaman Apr 05 '17 at 13:25