How to assign super to a variable?

前端 未结 4 1911
长发绾君心
长发绾君心 2021-01-22 07:52

I\'d like to do the following:

public class Sub extends Super {
  public Sub(Super underlying) {
    if (underlying == null) {
      underlying = super; // this          


        
4条回答
  •  悲哀的现实
    2021-01-22 08:44

    I think something like what you want can be done if you are willing to add, and call, subclass-specific method names for the methods involved:

    public class Test {
      public static void main(String[] args) {
        Super sup = new Super();
        Sub sub1 = new Sub(null);
        Sub sub2 = new Sub(sup);
        sub1.subMethod();
        sub2.subMethod();
        sup.method();
      }
    }
    
    class Super {
      public void method(){
        System.out.println("Using method from "+this);
      }
    }
    
    class Sub extends Super {
      private Super underlying;
      public Sub(Super underlying) {
        if (underlying == null) {
          underlying = this;
        }
    
        this.underlying = underlying;
      }
    
      public void subMethod() {
        underlying.method();
      }
    }
    

提交回复
热议问题