Can we override static methods?

Answer Posted / sadheez

It may seems to be overriding the static methods, but the
real fact is HIDING.

class Foo {
public static void classMethod() {
System.out.println("classMethod() in Foo");

}

public void instanceMethod() {
System.out.println("instanceMethod() in Foo");
}
}

class Bar extends Foo {
public static void classMethod() {
System.out.println("classMethod() in Bar");

}

public void instanceMethod() {
System.out.println("instanceMethod() in Bar");
}
}

class StaticHiding {
public static void main(String[] args) {
Foo f = new Bar();

f.instanceMethod();
f.classMethod();


when u run this program output will be:

instanceMethod() in Bar
classMethod() in Foo.

Here if u say it to be overriding then the
subclass ie., Bar class having static classMethod() should
be executed. But the fact here is Foo class static
classMethod() is executed.

So its method HIDING and not method
overriding..

I hope i have given answer to my best if
anyone feels wrong plz do post ur suggestions..

Is This Answer Correct ?    59 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Is void a keyword in java?

592


What is multi level inheritance in java?

556


Explain which of the following methods releases the lock when yield(), join(),sleep(),wait(),notify(), notifyall() methods are executed?

611


Is hashmap thread safe?

556


What is the indent key?

589






What is set string?

596


What is a platform?

542


Can we define package statement after import statement in java?

557


What are the different http methods?

530


When is the arraystoreexception thrown?

566


What is prefix of a string?

573


What is the impact of declaring a method as final?

558


What is the main method java?

530


Can an interface be defined inside a class?

517


What is the purpose of abstract class?

519