1) In Java , we have default constructors provided for classes by the compiler (in case one is not declared).
2) The abstract classes can't be instantiated by using the new operator because they don't provide full implementation of all the methods.
Then does it make sense to have constructors inside abstract classes. Let us find it using a sample abstract class:
The decompiled code for this class will show the truth about constructors in abstract classes in Java
Why?
The reason is that when a class extends any other class and an instance of the subclass is created then the constructor calls are chained and the super class constructors are invoked. This rule is no exception for abstract class
Moreover, having constructors in a class doesn't necessarily mean that instance of that class will be created using the new operator, but the constructors are intended for writing any initializing code.
2) The abstract classes can't be instantiated by using the new operator because they don't provide full implementation of all the methods.
Then does it make sense to have constructors inside abstract classes. Let us find it using a sample abstract class:
public
abstract
class
Test{
public
abstract
void
doSomething();
}
The decompiled code for this class will show the truth about constructors in abstract classes in Java
public
abstract
class
Test
{
public
Test()
{
}
public
abstract
void
doSomething();
}
Why?
The reason is that when a class extends any other class and an instance of the subclass is created then the constructor calls are chained and the super class constructors are invoked. This rule is no exception for abstract class
Moreover, having constructors in a class doesn't necessarily mean that instance of that class will be created using the new operator, but the constructors are intended for writing any initializing code.
No comments:
Post a Comment