Can Static Method be overridden
class MyClass {
static void myStaticMethod() {
System.out.println("Im in sta1");
}
}
class MySubClass extends MyClass {
static void myStaticMethod() {
System.out.println("Im in sta123");
}
}
public class My {
public static void main(String arg[]) {
MyClass myObject = new MyClass();
myObject.myStaticMethod();
// should be written as
MyClass.myStaticMethod();
// calling from subclass name
MySubClass.myStaticMethod();
myObject = new MySubClass();
myObject.myStaticMethod(); // since it is not dispatched on myObject
// still calls the static method in MyClass, NOT in MySubClass }
}
Static method cannot be overridden, it can be overloaded ( similarly final )
Static methods cannot be overridden because they are not dispatched on the object instance at runtime. The compiler decides which method gets called.
No comments:
Post a Comment