如果可能的话,为什么不能覆盖它?

Why can't it be overridden, if possible?

提问人:Lenny 提问时间:12/8/2022 更新时间:12/8/2022 访问量:27

问:

我正在学习 Java,我遇到了一个 Closure 的例子:

public class Callbacks {

    public static void main(String[] args) {
        Callee1 c1 = new Callee1();
        Callee2 c2 = new Callee2();
        MyIncrement.f(c2);
        Caller caller1 = new Caller(c1);
        Caller caller2 = new Caller(c2.getcallbackReference());
        caller1.go();
        caller1.go();
        caller2.go();
        caller2.go();

    }

}

interface Incrementable {
    void increment();
}

class Callee1 implements Incrementable {
    private int i = 0;

    @Override
    public void increment() {
        i++;
        print(i);
    }
}

class MyIncrement {
    public void increment() {
        System.out.println("another operation");
    }

    public static void f(MyIncrement m) {
        m.increment();
    }
}


class Callee2 extends MyIncrement {
    private int i = 0;
    
    
    public void increment() {
        super.increment();
        i++;
        print(i);
    }

    private class Closure implements Incrementable {
        
        @Override
        public void increment() {
            Callee2.this.increment();
        }
    }

    Incrementable getcallbackReference() {
        return new Closure();
    }
}

class Caller {
    Incrementable callbackRegerence;

    Caller(Incrementable cbh) {
        callbackRegerence = cbh;
    }

    void go() {
        callbackRegerence.increment();
    }
}

示例作者的评论:

当 Mylncrement 继承到 Callee2 中时,increment( ) 无法被 Incrementable 覆盖以供使用,因此您被迫使用内部类提供单独的实现。

我的问题是:什么?为什么我们不能?我们可以在 Callee2 类中覆盖它,还是我误解了作者? 请解释他想用这句话说什么。

Java 回调 闭包覆盖

评论


答:

0赞 Taron Qalashyan 12/8/2022 #1

您需要有一个 Incrementable 类型作为 Caller 参数。 您可以将其更改为相同。

class Callee2 extends MyIncrement {
    private int i = 0;
    
    
    public void increment() {
        super.increment();
        i++;
        print(i);
    }

    private class Closure implements Incrementable {
        
        @Override
        public void increment() {
            Callee2.this.increment();
        }
    }

    Incrementable getcallbackReference() {
        return new Closure();
    }
}

新增功能:

class Callee2 extends MyIncrement implements Incrementable {
    private int i = 0;


    public void increment() {
        super.increment();
        i++;
        System.out.println(i);
    }
}

评论

0赞 Lenny 12/8/2022
然后,如果您删除 Closure 类并将实现添加到 Callee2,则该示例会变得有点奇怪。我明白了,谢谢!