English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
When we have two classes, one extending another class, if these two classes have the same method, including parameters and return type (for example, sample), then the method in the subclass will override the method in the superclass.
i.e., due to inheritance. If we instantiate the subclass, a copy of the superclass member will be created in the subclass object, so both methods can be used for the subclass object.
However, if the method is called(Sample)Then the sample method of the subclass will be executed to override the method of the superclass.
class Super{ public static void sample(){ System.out.println("Method of the superclass"); } } public class OverridingExample extends Super { public static void sample(){ System.out.println("Method of the subclass"); } public static void main(String args[]){ Super obj1 = (Super) new OverridingExample(); OverridingExample obj2 = new OverridingExample(); obj1.sample(); obj2.sample(); } }
Output result
Method of the superclass Method of the subclass
When the superclass and subclass contain the same method (including parameters) and whether they are static, the method in the superclass will be hidden by the method in the subclass.
This mechanism is abbreviated as "method hiding", although the superclass and subclass have static methods with the same signature, it is not considered as overriding.
class Super{ public static void demo() { System.out.println("This is the main method of the superclass"); } } class Sub extends Super{ public static void demo() { System.out.println("This is the main method of the subclass"); } } public class MethodHiding{ public static void main(String args[]) { MethodHiding obj = new MethodHiding(); Sub.demo(); } }
Output result
This is the main method of the subclass
The key to method overloading is that if the superclass and subclass have methods with the same signature, both are available for objects of the subclass. The method to be executed is determined by the type of the object (reference) used to save the object.
SuperClass obj1 = (Super) new SubClass(); obj1.demo() // invokes the demo method of the superclass SubClass obj2 = new SubClass(); obj2.demo() //invokes the demo method of the subclass
However, in the case of static methods, since they do not belong to any instance, you need to access them using the class name.
SuperClass.demo(); SubClass.Demo();
Therefore, if the superclass and subclass have static methods with the same signature, the subclass object can use the copy of the superclass method. Since they are static, the method call will be resolved at compile time, so static methods cannot be overridden.
However, since a copy of the static method can be used, if you call the method of the subclass, it will be redefined/The method of hiding the superclass.