简体   繁体   中英

Accessing instance methods using subclass and superclass references

Here is the sample code:

package com.ankur.javapractice;
public class SuperClass {

    public void someMethod(int val) {
        System.out.println("Public method in SuperClass");
    }
}

class SubClass extends SuperClass {

    public void someMethod() {
        System.out.println("Public method in SubClass");
    }

    public static void main(String[] args) throws InterruptedException {
        SuperClass superClassRef = new SubClass();
        SubClass subClassRef = new SubClass();
        //superClassRef.someMethod(); // (1)
        subClassRef.someMethod(8); // (2)
    }
}

I understand why (1) won't work at compile time (that's why I have it commented out). It won't work because someMethod() is not known to superClassRef since it is of type SuperClass and SuperClass does not define someMethod() .

My question is why/how does (2) work then at compile time? Using the same explanation as above, at compile time , someMethod(int) is also not known to subClassRef since it is of type SubClass and SubClass does not define someMethod(int) .

Edit and Update:

Some answers pointed out that SubClass inherits someMethod(int) from SuperClass . That is correct and I understand that; my follow up question to that is how is compiler able to take inheritence relationships into account?

Yes someMethod(int) is defined in parent class which is SuperClass , but when child class inherits parents class using extends keyword then subclass inherits all of the public and protected members of its parent and can use them directly, which is called Inheritance

A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members:

  • The inherited methods can be used directly as they are.

This is because SubClass inherits someMethod(int) and has someMethod(), so it has two different methods. SuperClass cannot access someMethod() because it is not extending any classes.

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