简体   繁体   中英

Java Inheritance - Base class methods being overriding by derived class when using base variable for derived object

I've been preparing for the OCA Java SE 8 certification, and I've been doing a lot of studying, one of the hardest part for me, have been Inheritance, mainly because I started programming with PHP, so my programming haven't been so object oriented. Anyway, my issue is the following:

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;
    }
}

Using Employee variable to create a HRExecutive object, it doesn't allow me to reach any of HRExecutive members, trying to compile will fail due to not found symbol, which makes sense.

BUT when I remove the comments, and declare getInt() in base class Employee, it get's overridden by HRExecutive's method. It prints "HRExecutive getInt" and "10".

If previously Employee didn't have access to HRExecutive members, why after declaring the same method in class it is getting overridden? This is what I would like to understand.

At compile time you only know the static type of the instance which is Employee in this case. When Employee does not have a getInt() method you cannot call it.

But if getInt() is declared for an Employee it can be called and at runtime the method corresponding to the dynamic type of the instance, which is HRExecutive will get called.

"If previously Employee didn't have access to HRExecutive members, why after declaring the same method in class it is getting overridden?"

The reason for this is dynamic binding. Even though The method 'getInt()'is called by an 'Employee' variable, it is invoked on a 'HRExecutive' object. Hence, during run time, the method call will be resolved the subclass method ie method in 'HRExecutive' . If there is no overriding in 'HRExecutive', superclass method will get called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM