In Java, why can't I declare a final member (w/o initializing it) in the parent class and set its value in the subclass? How can I work around?

前端 未结 8 1250
长情又很酷
长情又很酷 2020-12-07 01:29

In a Java program, I have multiple subclasses inheriting from a parent (which is abstract). I wanted to express that every child should have a member that is set once only (

相关标签:
8条回答
  • 2020-12-07 02:05

    Yes, the final members are to be assigned in the class in which they are declared. You need to add a constructor with a String argument to Parent.

    0 讨论(0)
  • 2020-12-07 02:07

    Another Java-ish way to do this is probably to have the parent class to define an abstract "getter", and have the children implement it. It's not a great way to do it in this case, but it in some cases it can be exactly what you want.

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