2012-05-26 56 views
0

我想从子引用变量访问父类的成员函数。使用函数覆盖时如何访问父类的函数

我的代码:

class Emp 
{ 
static String Cname="Google"; 
int salary ; 
String Name; 

void get(String s1,int s2) 
{ 
    Name=s1; 
    salary=s2; 
} 
void show() 
{ 
    System.out.println(Name); 
    System.out.println(salary); 
    System.out.println(Cname); 

} 

} 
public class Practice extends Emp{ 

/** 
* @param args 
*/ 
void show() 
{ 
    System.out.println("in Child class"); 
} 
public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    Practice e=new Practice(); 
    e.show(); 
    e.get("Ratan",200000); 
    ((Emp)e).show(); 
} 

} 

输出是:

in Child class 
in Child class 

这意味着两次孩子的成员函数被调用。有什么办法来解决这个问题?

回答

0

你不能真正做你想做的事情。正如其他人所说,在子类中,您可以使用super.methodName()调用基类方法;所以你可以在你的Practice类中编写一个方法,例如:showBase(){super.show(); }但是这首先会有点挫败show()的重点。

您可能想要改变基类中某个方法的行为,并使用覆盖或在子类中有额外的方法来丰富基类的功能。尝试做你的建议表明你需要重新考虑你的设计。

+0

谢谢我得到了它。 –

0

您必须调用超类的方法,如下所示: super.show();

0

在孩子班之外是不可能的。 (在子类中使用super.show())。

+0

java.lang.NoSuchMethodException –

+0

抱歉反射无效,请参阅http://stackoverflow.com/questions/5411434/how-to-call-a-superclass-method-using-java-reflection – mart