Finite field inheritance in Java?

What happens when a superclass has a field labeled final, but the subclass overrides (hides?) That field? The โ€œfinaleโ€ doesn't stop it, does it? The specific example I'm working on is the Building class, from which various types of buildings are inherited. The cost of each type, among other things, must be final for each subclass, but each type of building must have its own costs.

Edit: Since then, I realized that I have no idea what I talked about above. I really want static cost variables. However, if I declare these static variables in the superclass, they are static for the superclass, so Subclass1.cost, for example, refers to the same value as Superclass.cost or Subclass2.cost. How can I make variables static for each subclass without having to declare them in each class.

+6
source share
3 answers

The final keyword, when applied to fields in a Java class, has nothing to do with inheritance. Instead, it indicates that outside the constructor, this field cannot be reassigned.

Java considers hiding and redefining a name separately. Redefinition actually changes the observed behavior of the program at runtime by switching this function, and the name is hidden, changing the program, changing the static interpretation of which field is the link. final in relation to redefinition works only for methods, because fields in Java cannot be redefined. Using final in these different contexts is unfortunately a bit confusing, and there is no way to prevent a field from containing its name in a subclass.

If you want buildings to have different costs, one option would be to have an overridden getCost method, which is redefined differently in each derived class. Alternatively, you can have only one protected or private in the base class that saves the cost, then each subclass sets this field either directly (if it is protected ) or through the constructor of the base class (if it is a private field).

Hope this helps!

+11
source

You can do this in two ways: create an access function and hide the field, or pass the cost of the building to a superclass from a subclass. You can combine them and create a property that cannot be overridden by subclasses:

 public class Building { private final int cost; protected Building(int cost, ...) { this.cost = cost; } public final int getCost() { return cost; } } public class Cottage extends Building { public Cottage() { super(COTTAGE_COST, ...); } } 
+3
source

Agree with the other answers, but I think the following implementation is better in this case:

  public abstract class Building { private final int cost; public Building(int cost) { this.cost = cost; } public final int getCost() { return cost; } } class Skyscraper extends Building { public Skyscraper() { super(100500); } } 

Of course, the field can be made public, but what a different story ...

+1
source

Source: https://habr.com/ru/post/905590/


All Articles