adspace


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

Explain public static void main(string args[]) in java.

1084


What do you mean by an interface in java?

1107


What is java string pool?

1088


Write a program to find the whether a number is an Armstrong number or not?

1107


What is a constructor overloading in java?

1131


explain different ways of using thread? : Java thread

1089


How to sort array in descending order in java?

999


What are the differences between heap and stack memory in java?

1151


What is a classloader in java?

1096


What is the difference between break and continue statements?

1131


How to create a base64 decoder in java8?

1144


Differentiate between static and non-static methods in java.

1131


Is minecraft 1.15 out?

1050


Write a program to print count of empty strings in java 8?

1092


What is an object in java and how is it created?

1147