Inheritance of final fields in Java?

前端 未结 3 1387
傲寒
傲寒 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: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, ...);
        }
    }
    

提交回复
热议问题