Java force fields inheritance

前端 未结 4 1561
离开以前
离开以前 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 01:53

    You should use a constructor and possibly a getter

    class t1{
     public final int a;
    
     public t1() {
        this(5);
     }
     protected t1(int a) {
        this.a = a;
     }
    
     public void get(){
        System.out.println(a);
     }
    }
    
    class t2 extends t1{
      public t2() {
         super(1);
      }
    }
    

    now

    t2 z = new t2();
    z.get();
    

    prints 1

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2021-01-29 02:04

    Yes, there is a way do to this. You can apply pattern which called "Template method". Here is an example

    class Base {
    
         void someMethod() {
             int value = getValue();
    
             // calculate something
         }
    
         protected abstract int getValue();
    }
    
    class Derived extends Base {
    
        int getValue() {
             return 5;
        }
    }
    

    Where getValue() is your template method and you can insert any logic in your inherited classes implementations.

    0 讨论(0)
  • 2021-01-29 02:14

    you are shadowing/hiding the variable of t1!

    t1 can see the variable of t2 and prints it's own a-value in the get method.

    you don't need to declare a again because the a of t1 can be seen everywhere

    if you want another default value for a in object of type t2 override the default constructor.

    public t2() {
        this.a = 1;
    }
    
    0 讨论(0)
提交回复
热议问题