简体   繁体   English

超类调用子类方法

[英]Superclass calls subclass method

I have a subclass extending a superclass. 我有一个扩展超类的子类。 I want the superclass to never call methods on the subclass. 我希望超类永远不要在子类上调用方法。 Is this possible? 这可能吗?

It seems unintuitive that a method explicitly invoked on the superclass would call the subclass again. 在超类上显式调用的方法将再次调用子类似乎是不直观的。

Trivial example: 琐碎的例子:

public class Demo {
    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        System.out.println("A.a() = " + a.a()); // -1
        System.out.println("A.b() = " + a.b()); // -1
        System.out.println("B.a() = " + b.a()); // 99
        // B.b() -> A.b() -> B.a()
        System.out.println("B.b() = " + b.b()); // 99
    }
}

class A {
    public int a() { return -1; }
    public int b() { return a(); } // tried, doesn't work: A.a(), A.this.a()
}

class B extends A {
    public int a() { return 99; }
    public int b() { return super.b(); }
}

Note: Actual case is implementing a Deque; 注意:实际情况是实现双端队列; the descending iterator class inherits from the forward iterator class, just starting from the tail instead of the head. 降序迭代器类继承自前向迭代器类,仅从尾部而不是头部开始。 I'd like to swap the method names, which I'd like to do with: 我想交换方法名称,这是我想做的:

public boolean hasNext() {
    return super.hasPrevious();
}

But that doesn't work because the forward iterator calls the wrong methods on the backwards iterator. 但这不起作用,因为前向迭代器在向后迭代器上调用了错误的方法。 My current workaround is storing the forward iterator as a field and call methods on that, but that seems clumsy / inelegant. 我当前的解决方法是将前向迭代器存储为字段并在其上调用方法,但这似乎笨拙/不雅致。

By default, subclass can override methods of its superclass. 默认情况下,子类可以覆盖其超类的方法。 To prevent that from happening, you can add a final modifier to the superclass's methods to prevent its subclasses from overriding that method. 为了防止这种情况发生,可以在超类的方法中添加final修饰符,以防止其子类覆盖该方法。

If the superclass method being called is private , then when you're in the superclass code, it will go for that superclass method and not the subclass method. 如果被调用的超类方法是private ,那么当您进入超类代码时,它将用于该超类方法而不是子类方法。

The following will work, even if it's ugly. 即使很丑陋,也可以执行以下操作。

class A {
    public int a() { return privateA(); }
    public int b() { return privateA();}  
    // It's impossible for anything to override privateA, even if a subclass has a 
    // method with the same name, because it's private.
    private int privateA(){return -1}
}

class B extends A {
    public int a() { return 99; }
    public int b() { return super.b(); }
}

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

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