【问题标题】:Java Inheritance - Base class methods being overriding by derived class when using base variable for derived objectJava Inheritance - 使用基变量作为派生对象时,基类方法被派生类覆盖
【发布时间】: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


【解决方案1】:

在编译时你只知道实例的静态类型,在这种情况下是Employee。当Employee 没有getInt() 方法时,您不能调用它。

但如果为Employee 声明了getInt(),则它可以被调用,并且在运行时对应于实例的动态类型的方法,即HRExecutive 将被调用。

【讨论】:

    【解决方案2】:

    “如果以前 Employee 没有访问 HRExecutive 成员的权限,为什么在类中声明相同的方法后它会被覆盖?”

    原因是动态绑定。即使方法 'getInt()' 由 'Employee' 变量调用,它也会在 'HRExecutive' 对象上调用。因此,在运行时,方法调用将被解析为子类方法,即 'HRExecutive' 中的方法。如果“HRExecutive”中没有覆盖,则将调用超类方法。

    【讨论】:

      猜你喜欢
      • 2011-04-21
      • 2014-02-02
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 2019-08-31
      • 1970-01-01
      • 1970-01-01
      • 2017-07-05
      相关资源
      最近更新 更多