Java force fields inheritance

前端 未结 4 1705
离开以前
离开以前 2021-01-29 01:45

I know there have been lots of thread about Java inheritance (and i already read it), but they all stand for \"how it is\", and I need knowledge \"how to change it\". So, we hav

4条回答
  •  星月不相逢
    2021-01-29 02:01

    Polymorphism works only for methods, not for fields and you cant change this Java mechanism. It means that late binding will find correct body of method depending on class of object

    class X{
        void sayHello(){
             System.out.println("Hello from X");
        }
    }
    
    class Y extends X{
        void sayHello(){
             System.out.println("Hello from X");
        }
    }
    
    //...
    X obj = new Y();
    obj.sayHello();// even if you are using X reference body of method will 
                   // come from Y class
    

    But fields are not polymorphic so if method uses some field it will use this field all the time (once again, late binding will not search for newest field declared in class of current object). That is why you are seeing 5 as result.

    If you want to simulate" polymorphic behaviour of field used in methods body your best choice is to let derived class set new value of that field in base class like in Peter Lawrey's answer (big +1 for him).

提交回复
热议问题