I was reading A Programmer’s Guide to Java™ SCJP Certification by Khalid Mughal.
In the Inheritance chapter, it explains that
Inherit
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();
?
You can override static methods, but if you try to use polymorphism, then they work according to class scope(Contrary to what we normally expect).
public class A {
public static void display(){
System.out.println("in static method of A");
}
}
public class B extends A {
void show(){
display();
}
public static void display(){
System.out.println("in static method of B");
}
}
public class Test {
public static void main(String[] args){
B obj =new B();
obj.show();
A a_obj=new B();
a_obj.display();
}
}
IN first case, o/p is the "in static method of B" # successful override In 2nd case, o/p is "in static method of A" # Static method - will not consider polymorphism
Many have voiced out their answer in words. This is an extended explanation in codes:
public class A {
public static void test() {
System.out.println("A");
}
public static void test2() {
System.out.println("Test");
}
}
public class B extends A {
public static void test() {
System.out.println("B");
}
}
// Called statically
A.test();
B.test();
System.out.println();
// Called statically, testing static inheritance
A.test2();
B.test2();
System.out.println();
// Called via instance object
A a = new A();
B b = new B();
a.test();
b.test();
System.out.println();
// Testing inheritance via instance call
a.test2();
b.test2();
System.out.println();
// Testing whether calling static method via instance object is dependent on compile or runtime type
((A) b).hi();
System.out.println();
// Testing whether null instance works
A nullObj = null;
nullObj.hi();
Results:
A
B
Test
Test
A
B
Test
Test
A
A
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.Static members are universal members. They can be accessed from anywhere.
Static members will not be inherited to subclass because inheritance is only for non-static members.. And static members will be loaded inside static pool by class loader. Inheritance is only for those members which are loaded inside the object
All the public and protected members can be inherited from any class while the default or package members can also be inherited from the class within the same package as that of the superclass. It does not depend whether it is static or non static member.
But it is also true that static member function do not take part in dynamic binding. If the signature of that static method is same in both parent and child class then concept of Shadowing applies, not polymorphism.