2015-07-13 140 views
0

我想知道为什么这个没有工作,如为什么没有编译器的计算机类中调用重启方法...参考变量和对象

考虑以下情形:

我有3类,如下所示:

public class Computer { 
public int compStatus = 0; //0 means off, 1 means on. 

public void turnOn(){ 
    this.compStatus = 1; 
} 

public void turnOff(){ 
    this.compStatus = 0; 
} 

public void restart(){ 
    if(compStatus ==1){ 
    System.out.println("Turning off"); 
    compStatus = 0; 
    System.out.println("Turning on"); 
    compStatus = 1; 
    System.out.println("Restart successful"); 
    } 
} 


} 

现在子类:

public class Macintosh extends Computer { 

public void openXCode(){ 
    if(compStatus == 1){ 
     System.out.println("XCode Compiler opened."); 
    } 
    else{ 
     System.out.println("Mac is off."); 
    } 
} 

public void restart(){ 
    System.out.println("Mac restarted"); 
} 

} 

的测试类:

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

    Computer testObj = new Macintosh(); 
    testObj.turnOn(); 
    testObj.restart(); ///ERROR HERE 
} 
} 

我知道,编译器会检查重启方法是在类的引用变量“计算机”不是类的实际对象的引用的另一端“的Macintosh ”。所以如果我所说的是真的,为什么重新启动方法不被调用?

+0

此代码的预期输出是什么? '关闭''打开''重新启动成功'? –

+0

@MattMartin我会希望编译器调用超类的重启方法,我知道你通常会做super.restart(),但我很好奇为什么Computer类重启方法没有被调用。 – RamanSB

+1

尝试'((计算机)testObj).restart();'在问题行。这是你期待的行为吗?如果是这样,我可以给你写一个完整的答案,解释为什么这会起作用,以及为什么你的原始代码没有达到你的预期。据我所知,你知道你可以这样做,但不知道为什么原始代码不起作用。 –

回答

0

您必须调用基类方法才能真正重新启动。你的方法只是隐藏了基本方法。您应该重写该方法,然后将其称为base.restart以执行您想要的操作。

+0

重新启动方法已在子类中覆盖..., 什么是我的方法和什么是基本方法,您没有明确指定使用这些术语时指的是哪种方法...'我的'和'基地'。 – RamanSB

+1

super.restart();我非常清楚我想表达的是什么。 –

+0

如何使用testObj.restart(),如果编译器只检查引用变量类(super)中的方法,就不会使用超类重启方法,我会假定它会这样做。 – RamanSB