When ever you use new
keyword you create an object. Objects are created in heap. new Horse()
will create an object of Horse
in the heap and will do initialization as per the class Horse.java
.
Now with the case presented assuming Horse
inherits from Animal
. Referencing the object of Horse
by a variable of type Animal
(Animal a = new Horse()
) does not affect the object creation ( it is created same even if you do Horse h = new Horse()
). It only restricts the invoking of the additional method present in the class Horse
using variable of super class type. You need to cast it if you wish to invoke the methods of class Horse
. But point to take care is that we can invoke whats there in the object created by the underlying blueprint class. Thats why if you override a method then it doesnt matter if you have a variable of super type or if you cast a variable of Horse
to Animal
or you simply use variabl of type Horse
to reference an obkect of Horse
, invoking a method which is overrided will always result in the overriden behaviour.
These are the things we as a programmers must understand, rest should be left to the JVM implementation. How it woks internally may change on different platforms but the contract and end result on top level is always the same.