Reference Static Methods/Variables in Java from an Instance

后端 未结 5 1151
傲寒
傲寒 2020-12-11 20:17

Can anyone explain to me why java allows you to access static methods and members from an instance? A bad example, if I have a class called RedShape and it has a static meth

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-11 20:55

    There's really no reason why you can actually do this.

    My only guess was that it would allow you to override static methods, but you can't.

    If you try the following scenario:

    Banana has a static method called 'test' (this prints 'banana') Apple extends Banana and "overrides" the static method called 'test' (this prints 'apple')

    and you do something like this:

    public static void main(String[] args) {
        Apple apple = new Apple();
        Banana banana = new Banana();
        Banana base = new Apple();
    
        apple.test();
        banana.test();
        base.test();
    }
    

    The resulting output is:

    apple
    banana
    banana
    

    So effectively, it's pretty useless.

提交回复
热议问题