我有以下代码,其中基类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
由于
Jayendra
答案 0 :(得分:1)
你想隐藏什么? 请尝试以下代码
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();
}
}