【发布时间】:2017-10-10 04:52:53
【问题描述】:
我一直在准备 OCA Java SE 8 认证,并且一直在做很多学习,对我来说最难的部分之一就是继承,主要是因为我开始使用 PHP 编程,所以我的编程还没有那么面向对象。无论如何,我的问题如下:
class MyOffice{
public static void main(String args[]){
Employee emp = new HRExecutive();
int x = emp.getInt();
System.out.println(x);
}
}
class Employee {
public String name;
String address;
protected String phoneNumber;
public float experience;
int y = 12;
/* COMMENTED CODE THAT GETS OVERRIDDEN WHEN UNCOMMENTED
public int getInt(){
System.out.println("Employee getInt");
return y;
}
*/
}
interface Interviewer{
public void conductInterview();
}
class HRExecutive extends Employee implements Interviewer{
public String[] specialization;
int elInt = 10;
public void conductInterview(){
System.out.println("HRExecutive - conducting interview");
}
public int getInt(){
System.out.println("HRExecutive getInt");
return elInt;
}
}
使用 Employee 变量创建 HRExecutive 对象,它不允许我访问任何 HRExecutive 成员,尝试编译将由于找不到符号而失败,这是有道理的。
但是当我删除 cmets 并在基类 Employee 中声明 getInt() 时,它会被 HRExecutive 的方法覆盖。它打印“HRExecutive getInt”和“10”。
如果以前 Employee 没有访问 HRExecutive 成员的权限,为什么在类中声明了相同的方法之后它会被覆盖?这是我想了解的。
【问题讨论】:
-
这就是多态性的全部意义所在。您可以在基类中声明方法;当代码调用该方法时,程序实际上可以运行该方法的不同实现,具体取决于该对象实际上是该基类的对象还是其子类之一的对象。您确实应该通过教程来了解基本概念。 Oracle 有一个 here,尽管可能有更好的。
标签: java inheritance