Inheritance of final fields in Java?

前端 未结 3 1385
傲寒
傲寒 2021-01-02 03:05

What happens when a superclass has a field marked final, but a subclass overrides (hides?) this field? \'Final\' doesn\'t stop this, does it? The specific example I\'m work

相关标签:
3条回答
  • 2021-01-02 03:46

    Agree with 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 could be made public, but that's the other story...

    0 讨论(0)
  • 2021-01-02 03:54

    You can do this two ways: make an accessor function and hide the field itself or else pass the building cost to the superclass constructor from the subclass. You can combine these and make a property that can't 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, ...);
        }
    }
    
    0 讨论(0)
  • 2021-01-02 03:55

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

    Java treats name hiding and overriding separately. Overriding actually changes the observable behavior of the program at runtime by switching which function is called, while name hiding changes the program by changing the static interpretation of which field is being reference. final as applied to overriding only works for methods, because fields in Java cannot be overridden. The use of final in these different contexts is a bit confusing, unfortunately, and there is no way to prevent a field from having its name hidden in a subclass.

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

    Hope this helps!

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