In case of static method overriding ..I have developed this below code
class Ab {
static void getF() {
System.out.println("I am saral");
}
}
class Ham extends Ab {
static void getF() {
System.out.println("I am saral saxena");
}
public static void main(String[] args) {
// Ham h = new Ham();
// h.getF(); //Ham
Ab a = new Ham();
a.getF(); // Ab class
}
}
Now my query is that in case of static method overriding when i am using polymorphic behavior, Ab a = new Ham(); at this stage I am still getting the method getF(); of class Ab, please advise.
You can’t override a static method.
Static methods belong to classes. You can call
Ab.getF()orHam.getF()– you chose which when you code.Naming static methods the same in a class hierarchy has no impact whatsoever (other than possible confusion for programmers). Static methods are floating bits of code that belong to classes, not instances. Only instance methods are sensitive to overriding.
For this reason, it is poor style to call a static method on an instance (as you have), because it makes the method appear to be an instance method. It’s allowed in the language, but leads to programmer confusion, and therefore bugs, especially if the static method has a name like an instance method – eg discovering that a method named
setName(String)was a static method could be grounds for justifiable homicide.