I\'d like to do the following:
public class Sub extends Super {
public Sub(Super underlying) {
if (underlying == null) {
underlying = super; // this
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();
}
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();
}
}
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.
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.