How to get around the lack of abstract fields in Java?

前端 未结 5 2081
遇见更好的自我
遇见更好的自我 2021-01-13 01:06

Assume, we have an abstract class A and we want to force all subclasses to have a certain field. This is not possible in Java, because we can not define abstrac

5条回答
  •  猫巷女王i
    2021-01-13 01:44

    Workaround 2 is very common because of 2 advantages:

    1) the one you mentioned - the field does not belong to the subclass - it belongs to the parent and that is important because it was "demanded" by the parent and because the parent can use it

    2) When sub-classing from the parent you are very aware of this field because when you implement the constructor you must pass it on. If I saw the first workaround I wouldn't know what to understand from it, in this way I understand that the parent class needs this field to work, so it must have a meaningful value.

    note: if you have a class that has 10 fields that need to be initialized something is probably wrong in your design.

提交回复
热议问题