Thursday, 5 April 2018

Static Method Override

In reference to my blog  STATIC METHOD CALL FROM NULL REFERENCE This time we have come up with new interesting things about Static method in JAVA.


What will be output??


public class BaseClass {

public static void testStatic(){
System.out.println("In Base Class");
}

}


public class DerivedClass extends BaseClass {
public static void testStatic(){
System.out.println("In Derived Class");
}

}


public class TestClass {

public static void main(String[] args) {
BaseClass base = new DerivedClass();
base.testStatic();
}
}

What will be Output "In Base Class"  or "In Derived Class" ??

OUTPUT: In Base Class 

Wonder!! As I explained in our last blog that Static method is associate with the Class not the Instance of Class so, the base.testStatic will get replaced by BaseClass.testStatic.

 Hence Base class static method will call.

This is the reason why we can't override static method in Derived Class.

For any suggestion or doubts, please comment below :)

1 comment:

Wait, notify and notifyAll method in Object Class

We usually get  surprise  when these methods are present in  Object  class however they only used in  Threading  Concepts.   Wonder WHY?...