java超级没有按预期工作

时间:2013-04-15 10:03:19

标签: java inheritance override

public  class Counter{
    private int value;


    public int getValue(){
        return value;
    }

    public void setValue (int value){
        this.value = value;
    }

    public  void increment() {

        /* */
    }

    public  void decrement() {
        /* */
    }
}


public class LoopingCounter extends Counter{

    private int limit;

    public LoopingCounter(int limit){
        this.limit = limit;
    }

    public void increment(){
        int value = super.getValue();
        if( value == limit){

            System.out.println("Value has reached the limit, cannot increment any further!");
            setValue(0);

        } else{
            value++;
            setValue(value);
        }
    }
    public void decrement(){
        int value = super.getValue();
        if(value == limit){
            System.out.println("Value has reached the limit, cannot decrement any further!");            
        } else{
            value--;
            setValue(value);
        }
    }

    public int getValue() {
        System.out.println("override");
        return 1000;
    }

}

public class CounterTest{
    public static void main(String[] args){

        LoopingCounter lc = new LoopingCounter(100);


        for(int i=0; i<150; i++){
            lc.increment();
            System.out.println(lc.getValue());
        }

    }
}

在这种情况下,LoopingCounter应该在Counter类中触发getValue方法。但由于某些原因,当我运行它时,它会继续使用自己的getValue方法。

请帮助我理解为什么我不能这样调用父方法。

道歉:

我现在看到了我的错误。我道歉。我没有意识到lc.getValue()并且很困惑为什么lc.increment无法正确调用super.getValue()。故事的士气在张贴之前得到足够的睡眠。 -_-“

5 个答案:

答案 0 :(得分:1)

行为是正确的。如果您要拨打Counter班级getValue(),则需要在super.getValue()LoopingCounter方法中的某个位置getvalue()lc.getValue()始终会调用getValue()类中定义的LoopingCounter方法,因为lcLoopingCounter的实例。

答案 1 :(得分:1)

您的父方法是调用,但由于您的继承类也具有getValue()方法,因此在执行父类方法后调用它。你应该改变你从基类中获取价值的方式。

答案 2 :(得分:0)

来自JLS 8.4.9 OverloadingJLS 8.4.8.1

  

如果覆盖子类中的父方法,并且使用子类实例运行该方法,则应该运行重写方法。

所以你在程序中得到了正确的行为。

要使用子实例调用父重写方法,您可以使用super keyword

答案 3 :(得分:0)

如果类B扩展了类A,则类Object Oriented Programming调用Overriding,类A具有方法void foo(),类B也提供void foo()方法的实现,这称为覆盖和如果你创建了B类的对象并调用了方法foo(),那么将调用子类的方法。

答案 4 :(得分:0)

每当你通过子类调用任何方法时,它总是首先调用子类方法,然后调用超类方法。

如果你想先调用超类方法,那么你可以在super.getValue()类的getValue()方法内写LoopingCounter