What is the use of creating a constructor for an abstract class in Java?

前端 未结 8 2043
时光取名叫无心
时光取名叫无心 2020-12-03 18:50

I would like to know what purpose a constructor for an abstract class serves; as we do not instantiate abstract classes, why would we ever need such a constructor?

相关标签:
8条回答
  • 2020-12-03 19:28

    If your class doesn't declare a constructor, javac will make a no-arg, do-nothing constructor for you. Then, when your subclass is initialized, it will call the generated no-op constructor and life is good.

    However, if your class declares any constructor, javac will NOT make one for you. In that case, the subclass constructor needs to explicitly call the constructor of the parent class. Otherwise, you'll fail to initialize members of the parent class, as the above answer mentions.

    0 讨论(0)
  • 2020-12-03 19:35

    If you have uninitialised final fields in an abstract class, you'll need to initialise them in a constructor.

    E.g.

    abstract class A {
        final int x;
    }
    

    will not compile without a constructor that assigns to x.

    0 讨论(0)
提交回复
热议问题