覆盖对 class 没有预期效果

Override not having expected effect on class

我正在测试扩展 class 和重写函数。使用下面的代码,当我调用 JonsClass2.jonsCalcFromClass(2) 时,我仍然没有得到编译错误,我仍然从 JonsClass2 得到响应,而不是我预期的来自 JonsClass3 的覆盖。

顺便说一句,我不得不使用 JonsClass2 JC2 = new JonsClass2(); 从 main 进行这些调用;然后 JC2.jonsCalcFromClass(2);否则编译器会抱怨我正在从静态上下文调用非静态。

class JonsClass3 extends JonsClass2 {

    @Override
    protected int jonsCalcFromClass(int a) {
        if (a==2) System.out.print("JonsClass3 Called from main using 2 as passed variable  ");
        if (a==1) System.out.print("JonsClass3  from main using 1 as passed variable  ");
        int c = (a + 2);
        return c;
    }

    @Override
    protected double jonsCalcFromClass(double b) {
        System.out.print("This is double line being called in JonsClass3> ");
        double c = (b + 300.10);
        return c;
    }

}

class JonsClass2 {

    protected int jonsCalcFromClass(int a) {
        System.out.print("This is the int line from JonsClass2 being called > ");
        int c = (a + 2);
        return c;
    }

    protected double jonsCalcFromClass(double b) {
        System.out.print("This is double line being called in JonsClass2> ");
        double c = (b + 3.10);
        return c;
    }

}

注意你创建的实例。

JonsClass2 js2 = new JonsClass2();
JonsClass2 js3 = new JonsClass3();
js2.jonsCalcFromClass(2);   // This is the int line from JonsClass2 being called >
js3.jonsCalcFromClass(2);   //JonsClass3 Called from main using 2 as passed variable 

在您的示例 onsClass2 JC2 = new JonsClass2(); 中,您创建了 JonsClass2 的实例,因此不会调用 JonsClass3 中的方法。

the compiler complains that I am calling a non static from a static context.

我们不能直接从静态方法(如 main)调用 non-static 方法。因为静态方法是 class' 方法。但是 non-static 方法是对象方法,所以我们应该在对象上调用它。所以:

public static void main(String[] args) { 
  jonsCalcFromClass(1) // compile error

  JonsClass2 JC2 = new JonsClass3()
  JC2.jonsCalcFromClass(1) // correct
}

如果你想要多态行为,你应该这样做: JonsClass2 JC2 = new JonsClass3 ();