Java force fields inheritance

前端 未结 4 1574
离开以前
离开以前 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

提交回复
热议问题