Can an abstract class have a constructor?

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

Can an abstract class have a constructor?

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

22条回答
  •  -上瘾入骨i
    2020-11-22 06:16

    You would define a constructor in an abstract class if you are in one of these situations:

    • you want to perform some initialization (to fields of the abstract class) before the instantiation of a subclass actually takes place
    • you have defined final fields in the abstract class but you did not initialize them in the declaration itself; in this case, you MUST have a constructor to initialize these fields

    Note that:

    • you may define more than one constructor (with different arguments)
    • you can (should?) define all your constructors protected (making them public is pointless anyway)
    • your subclass constructor(s) can call one constructor of the abstract class; it may even have to call it (if there is no no-arg constructor in the abstract class)

    In any case, don't forget that if you don't define a constructor, then the compiler will automatically generate one for you (this one is public, has no argument, and does nothing).

提交回复
热议问题