I was reading A Programmer’s Guide to Java™ SCJP Certification by Khalid Mughal.
In the Inheritance chapter, it explains that
Inheritance of members is closely tied to their declared accessibility. If a superclass member is accessible by its simple name in the subclass (without the use of any extra syntax like super), that member is considered inherited
It also mentions that static methods are not inherited. But the code below is perfectlly fine:
class A
{
public static void display()
{
System.out.println("Inside static method of superclass");
}
}
class B extends A
{
public void show()
{
// This works - accessing display() by its simple name -
// meaning it is inherited according to the book.
display();
}
}
How am I able to directly use display()
in class B
? Even more, B.display()
also works.
Does the book's explanation only apply to instance methods?
Static methods are inherited in Java but they don't take part in polymorphism. If we attempt to override the static methods they will just hide the superclass static methods instead of overriding them.
Static methods in Java are inherited, but can not be overridden. If you declare the same method in a subclass, you hide the superclass method instead of overriding it. Static methods are not polymorphic. At the compile time, the static method will be statically linked.
Example:
You'll get the following:
Many have voiced out their answer in words. This is an extended explanation in codes:
Results:
Therefore, this is the conclusion:
null
instance. My guess is that the compiler will use the variable type to find the class during compilation, and translate that to the appropriate static method call.We can declare static methods with same signature in subclass, but it is not considered overriding as there won’t be any run-time polymorphism.Because since all static members of a class are loaded at the time of class loading so it decide at compile time(overriding at run time) Hence the answer is ‘No’.
All methods that are accessible are inherited by subclasses.
From the Sun Java Tutorials:
The only difference with inherited static (class) methods and inherited non-static (instance) methods is that when you write a new static method with the same signature, the old static method is just hidden, not overridden.
From the page on the difference between overriding and hiding.
Static method is inherited in subclass but it is not polymorphism. When you writing the implementation of static method, the parent's class method is over hidden, not overridden. Think, if it is not inherited then how you can be able to access without
classname.staticMethodname();
?