English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Some basic rules in Java inheritance include-
There is no object relationship between parent classes, and there is no object relationship between subclasses and parent objects, which means that a reference of the parent class can hold a subclass object, while a subclass reference cannot hold a parent object.
In the case of overriding non-static methods, the runtime object will evaluate which method the subclass or superclass will execute. The execution of static methods depends on the type of reference held by the object.
Other basic rules of inheritance are related to static and non-static methods, that is, static methods in Java cannot be overridden, while non-static methods can be overridden. However, a subclass can define a static method with the same static method signature as the superclass without considering it as an override, and it is called hiding the superclass's static method.
According to the above rules, we will observe different situations with the help of the program.
class Parent { public void parentPrint() { System.out.println("parent print called"); } public static void staticMethod() { System.out.println("parent static method called"); } } public class SubclassReference extends Parent { public void parentPrint() { System.out.println("child print called"); } public static void staticMethod() { System.out.println("child static method called"); } public static void main(String[] args) { //SubclassReference invalid = new Parent();//Type mismatch: cannot convert from Parent to SubclassReference Parent obj = new SubclassReference(); obj.parentPrint(); //The method of the subclass would execute as the subclass object at runtime. obj.staticMethod(); //The method of the superclass would execute as the reference of the superclass. Parent obj1 = new Parent(); obj1.parentPrint(); //The method of the superclass would execute as the superclass object at runtime. obj1.staticMethod(); //The method of the superclass would execute as the reference of the superclass. SubclassReference obj3 = new SubclassReference(); obj3.parentPrint(); //The method of the subclass would execute as the subclass object at runtime. obj3.staticMethod(); //The method of the subclass would execute as the reference of the subclass. } }
Output Result
child print called parent static method called parent print called parent static method called child print called child static method called
The difference between using superclass reference and subclass reference is that using superclass reference can retain the object of the subclass, and can only access the methods defined by the subclass./The method of the superclass cannot be retained when using subclass reference, and can only access the methods defined by the subclass.