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:
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();
}
Woha!! that constructor was provided by 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.
总而言之,有构造函数的类不见得就能用new操作符来实例化
分享到:
相关推荐
Interfaces do not have constructors, and they cannot be instantiated directly. #### 10. What is the difference between an abstract class and an interface? **Answer**: In Java, an abstract class can...
Abstract classes We does not make a object of the abstract class. This class must be inherited. Unlike interface the abstract class may implement some of the methods defined in the class, but in this ...
- **第八章:深入多态——利用抽象类和接口**(Serious Polymorphism: Exploiting Abstract Classes and Interfaces) - 掌握抽象类和接口的概念及其应用场景。 - 学习如何实现接口并重写方法。 - 探讨继承和组合...
the ability to see how many new mail messages they have, are not supported by POP at all. These capabilities are built into programs like Eudora or Microsoft Outlook, which remember things like the ...
CHAPTER 13 Creating interfaces and defining abstract classes 287 CHAPTER 14 Using garbage collection and resource management 317 PARTⅢ DEFINING EXTENSIBLE TYPES WITH C# CHAPTER 15 Implementing ...