Can an abstract class have a constructor?

前端 未结 22 2494
甜味超标
甜味超标 2020-11-22 05:25

Can an abstract class have a constructor?

If so, how can it be used and for what purposes?

22条回答
  •  轮回少年
    2020-11-22 06:23

    Abstract class can have a constructor though it cannot be instantiated. But the constructor defined in an abstract class can be used for instantiation of concrete class of this abstract class. Check JLS:

    It is a compile-time error if an attempt is made to create an instance of an abstract class using a class instance creation expression.

    A subclass of an abstract class that is not itself abstract may be instantiated, resulting in the execution of a constructor for the abstract class and, therefore, the execution of the field initializers for instance variables of that class.

提交回复
热议问题