Inheritance of final fields in Java?

前端 未结 3 1386
傲寒
傲寒 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...

提交回复
热议问题