How to assign super to a variable?

前端 未结 4 1912
长发绾君心
长发绾君心 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:35

    It looks like you want to implement the delegation pattern.

    Simple extend Super, and let your IDE override all methods with the creation of super calls.

    Then replace "super." with "underlying."

    Error prone, but that's it.

    public class Sub extends Super {
        Super underlying;
        public Sub(Super underlying) {
            this.underlying = underlying;
        }
    
        @Override
        public void f() {
            underlying.f();
        }
    
    0 讨论(0)
  • 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();
      }
    }
    
    0 讨论(0)
  • 2021-01-22 08:51
    public class Sub extends Super {
      public Sub(Super underlying) {
        this.underlying = (underlying == null)
            ? new Super()
            : underlying;
      }
    
      @Override
      public void method() {
        underlying.method();
      }
    }
    

    Since another object is being created, it's not exactly the same, but it behaves as expected.

    0 讨论(0)
  • 2021-01-22 08:51

    You have not understood the super keyword in java correctly. Refer the javadoc for super

    If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged)

    Also, super() is used to call the parent class constructors.

    0 讨论(0)
提交回复
热议问题