I have a very basic question about abstract class in java.
As we know that we can't create an instance of an abstract class, then how JVM handles the instantiation of abstract class in java .
we can define a parameterized constrcutor in the abstract class and we can define another which extends the abstract class. In this situation who creates the instance of abstract class and invokes the constructor of the abstract class.
I want to understand, How JVM manages the object creation of abstract classes.
JVM cannot instantiate an abstract class it can instantiate only an instance of a non-abstract subclass of abstract class. Creating an instance means allocating space in memory necessary to hold all non-static fields and then initialing these fields by calling constructors.
JVM can not instantiate Interface or Abstract classes.
Take a look at this .
In the JVM, every object has a pointer to its class, but only to its concrete class and not to its interface or abstract class. If we get the memory address of an object, we can get the address of its class easily. This method is useful only for classes whose instances can be created. Neither interfaces nor abstract classes can be used in this way.
Refer this for more details .
In the case of Abstract class
and it's concrete SubClass
, when you do like this:
AbstractClass obj = new ConcreteClass();
new
operator creates an object of ConcreteClass
, and invokes its constructor to initialize the state of the created object. In this process, the constructor of the abstract class is also called from the ConcreteClass
constructor, to initialize the state of the object in the abstract class.
So, basically the object of AbstractClass
is not created. It's just that it's constructor is invoked to initialize the state of the object.
if Abstract class object is not created internally by the JVM, but only its constructor is invoked to initialise the state. Then without instantiation what is the point in initialisation and to which object initialisation is performed.
来源:https://stackoverflow.com/questions/20756679/how-jvm-handles-abstract-class-in-java