Important Info On Static Methods from Java Documentation taken from link:
https://docs.oracle.com/javase/tutorial/java/IandI/override.html
If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.
https://docs.oracle.com/javase/tutorial/java/IandI/override.html
If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.
The distinction between hiding a static method and overriding an instance method has important implications:
- The version of the overridden instance method that gets invoked is the one in the subclass.
- The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.
Consider an example that contains two classes. The first is
Animal, which contains one instance method and one static method:public class Animal {
public static void testClassMethod() {
System.out.println("The static method in Animal");
}
public void testInstanceMethod() {
System.out.println("The instance method in Animal");
}
}
The second class, a subclass ofAnimal, is calledCat:public class Cat extends Animal { public static void testClassMethod() { System.out.println("The static method in Cat"); } public void testInstanceMethod() { System.out.println("The instance method in Cat"); } public static void main(String[] args) { Cat myCat = new Cat(); Animal myAnimal = myCat; Animal.testClassMethod(); myAnimal.testInstanceMethod(); } }TheCatclass overrides the instance method inAnimaland hides the static method inAnimal. Themainmethod in this class creates an instance ofCatand invokestestClassMethod()on the class andtestInstanceMethod()on the instance.The output from this program is as follows:The static method in Animal The instance method in CatAs promised, the version of the hidden static method that gets invoked is the one in the superclass, and the version of the overridden instance method that gets invoked is the one in the subclass.
No comments:
Post a Comment