`

【翻译】Abstract Classes Have Constructors

阅读更多
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操作符来实例化
分享到:
评论

相关推荐

    java英文笔试

    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...

    JSP Simple Examples

    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 ...

    Head First Java In English

    - **第八章:深入多态——利用抽象类和接口**(Serious Polymorphism: Exploiting Abstract Classes and Interfaces) - 掌握抽象类和接口的概念及其应用场景。 - 学习如何实现接口并重写方法。 - 探讨继承和组合...

    Java邮件开发Fundamentals of the JavaMail API

    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 ...

    Microsoft Visual C# 2013 Step by Step,最新资料

    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 ...

Global site tag (gtag.js) - Google Analytics