我有以下代码,其中基类 Employee 有一个静态方法 meth1() ,我可以从子类(Pro)对象调用该方法。是方法隐藏还是什么情况? ,我不确定,因为我还没有在 Pro 类中实现 meth1() 方法,但仍然可以从 Pro 对象调用 Emplyee 静态方法。
class Employee
{
String s;
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
protected static void meth1()
{
System.out.println("inside emp-meth1");
}
}
public class Pro extends Employee {
/*
* public void meth1()
{
System.out.println("inside encapsulation-meth1");
}
*/
public static void main(String as[])
{
Pro e = new Pro();
// e.s ="jay";
e.meth1();
}
}
输出:
inside emp-meth1
谢谢
杰延德拉
最佳答案
你想隐瞒什么? 尝试下面的代码
emp.meth1()
将基于引用调用方法,而不是基于所引用的对象。
class Employee
{
String s;
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
protected static void meth1()
{
System.out.println("inside emp-meth1");
}
}
public class Pro extends Employee {
protected static void meth1()
{
System.out.println("inside encapsulation-meth1");
}
public static void main(String as[])
{
Pro e = new Pro();
Employee emp = new Pro();
emp.meth1(); //this is case of method hiding
e.meth1();
}
}
关于java - 这是方法隐藏的情况吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26407300/