简体   繁体   English

如何为变量分配超值?

[英]How to assign super to a variable?

I'd like to do the following: 我想做以下事情:

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

    this.underlying = underlying;
  }

  @Override
  public void method() {
    underlying.method();
  }
}

How can something like this be done? 怎么做这样的事情?

You have not understood the super keyword in java correctly. 您尚未正确理解Java中的super关键字。 Refer the javadoc for super 请参考javadoc以获取超级

If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. 如果您的方法覆盖了其超类的方法之一,则可以通过使用关键字super来调用覆盖的方法。 You can also use super to refer to a hidden field (although hiding fields is discouraged) 您也可以使用super来引用隐藏字段(尽管不建议使用隐藏字段)

Also, super() is used to call the parent class constructors. 另外, super()用于调用父类的构造函数。

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. 简单扩展Super,并让您的IDE通过创建super调用来覆盖所有方法。

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();
    }
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. 由于正在创建另一个对象,因此它并不完全相同,但是其行为符合预期。

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();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM