4

Considering these classes:

public class Animal{

}

public class Dog extends Animal{

}

public AnimalTest(){
    public static void main(String[] args){
       Dog d = new Dog();
       Animal a = d;
   }
}

my question is since I performed an upcasting on Animal a = d;does it consume a new memory allocation on the machine or does it use the memory allocated to the Dog d = new Dog();

anathema
  • 947
  • 2
  • 15
  • 27

3 Answers3

3

The Actual object or its memory footprint is not affected. just a new reference to the object is created. The only difference is that the reference a can only call methods or access attributes that was available in the Super Class Animal.

rogue-one
  • 11,259
  • 7
  • 53
  • 75
  • 2
    But what happens in the heap memory? Dog d =new Dog() creates a new Dog object in the heap and a variable d in the stack. The variable d references to the object in the heap. But variable a is down casted. Does that still mean it'll reference to the same object Dog object in the heap. If so how will the compiler know its downcasted. – Nibin Mar 31 '22 at 21:39
0

Animal a = d;

a is just a reference and the reference's memory is allocated in method stack(or jvm stack, not heap).

That is when invoke the method main, JVM will allocate a stack which contains the reference's space.

lichengwu
  • 4,277
  • 6
  • 29
  • 42
  • Thank you for the response, I would like to ask also that since Animal a is a reference and it is allocated on the stack where does Dog d allocated? on the heap? – anathema Jan 27 '14 at 07:13
  • @anathema Yes, `new Dog()` is allocated on JVM heap. – lichengwu Jan 27 '14 at 07:26
0

Implicit upcasting really helps in Runtime polymorphism/ method overriding when we have multiple child classes of a parent class. Here, instead of creating reference variables of each child class for referring to the child class object, we can have a single reference variable that is of parent class type in order to save the extra memory allocation for each reference variable in stack memory.