The Myth of Static and Final Methods.

What is the output of the program? and why?


public class ABC {
public static void test() {
System.out.println("ABC Static Test");
}

public void test2() {
System.out.println("ABC Test 2");
}
}

class CDE extends ABC {
public static void test() {
System.out.println("CDE Static Test");
}

public void test2() {
System.out.println("CDE Test 2");
}

public static void main(String[] args) {
ABC obj = new CDE();
obj.test();
obj.test2();
CDE obj1 = new CDE();
obj1.test();
obj1.test2();
}
}


Lets discuss it here...

We have been learning since so many years that static methods can not be overridden? when why? Some people call them as they are implicitly final... are they final?
To me, they are not final, they just hide themselves and behave like final. This is the reason why the above code does not generate a compile time error when we try to override it....

Override? are we overriding it? Nopes, we are not, and can not override it. Its simply a unique method, which could be created because of the hidden nature of superclass's static method. To check it, try to change STATIC into FINAL.... it generates error, you can not override a final method, blah blah. Because, Final methods are not hidden, they can not be overridden, Static methods are hidden, they can not be overridden too.

Polymorphism is a concept of OOP and static methods are not part of OOP. (Amazing isnt it?)

Now, lets speak about the Output of above method... whats output? did u actually think or just compiled and calculated it?

ABC Static Test
CDE Test 2
CDE Static Test
CDE Test 2


Because: When you override a method, you still get the benefits of run-time polymorphism, and when you hide, you do not.
The same object obj calls test() method of superclass and test2() method of child class... because, test2() is overridden and is given the priority, test() is a class method and compiler or JVM does not actually need a reference to it thus ignoring the obj reference here. The compiler will only look at the declared type of the reference, and use that declared type to determine, at compile time, which method to call. Since obj is declared as type ABC, the compiler looks at obj.test() and decides it means ABC.test().


For static methods, the compiler only uses the declared type of the reference. That's what we mean when we say a static method does not have run-time polymorphism

So, Remember that static methods are evaluated at Compile time. and class object are evaluated at Runtime.

Summarizing
1. Static method can't be overriden (They only get hidden)
2. Final method can't be overriden either.
3. But declaring the same STATIC method as the one in super class is ok.
4. whereas declaring the same FINAL method as the one in super class is illegal.

Comments