Can static methods be overrriden?


It is not possible to override static methods. If a subclass defines a static method with same signature as a static method which is defined parent class. Method in child class will be hiding the method in parent class. This phenomena is called method hiding. However if you override a static method compiler will not give an error. That means, if you try to override, Java doesn't stop you doing that. But you certainly don't get the 
same effect as you get for non-static methods.

 Overriding in Java simply means that the particular method would be called based on the run time type 
of the object and not on the compile time type of it (which is the case with overriden static methods). As static methods are class methods they are notinstance methods so they have nothing to do with the fact which reference is pointing to which Object or instance.as per the nature of static method it belongs to specific class, but you can redeclare it in to the subclass but that subclass doesn't know anything about the parent class' static methods because as I said it is specific  to only that class in which it has been declared .Accessing them using object references is just an extra liberty given by the designers of Java and we should certainly not think of stopping that practice only when they restrict it .

package com.faisalbhagat.test.

public class TestClassSuper {

public static void show()
{
System.out.println("I AM SUPER SHOW");
}

public  void overridden()
{
System.out.println("I AM SUPER OVERRIDEN");
}

}


public class TestClassChild extends TestClassSuper {

public static void show()
{
System.out.println(" I AM CHILD SHOW");
}

public  void overridden()
{
System.out.println("I AM CHILD OVERRIDEN");
}
}

public class TestClassTest {
public static void main(String[] args)
{
TestClassSuper c= new TestClassChild();
c.show();
c.overridden();
}

}


Output:-

I AM SUPER SHOW
I AM CHILD OVERRIDEN

----------------------------


i am storing child class object in super class reference. Now through this reference i am calling both static and non static method which are overriden, You saw the output : Non static method is called of child class because the reference was of child class . it was decided on run time due to late binding but the static method called is from super class because the declared reference was from super class it was STATICALLY bound to its static method at compile time. it didnt see which Object it is going to have in future.






0

Add a comment

Blog Archive
About Me
About Me
Loading