Can we override static methods?
Answer Posted / shailesh
Hi, we can overried the static method as well as we can
overload them. The exam which you have given is wrongly
interpreted. Never try to access the static method with the
instance variable, it can create confusion.
In the Foo, Bar example if you do like this
Foo f = new Bar();
and call f.(some staic method). It will always call the
static method of Foo (but not of Bar). Check the java docs.
So just modify the code like this
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 Test {
public static void main(String[] args) {
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 Test {
public static void main(String[] args) {
Foo f = new Foo();
f.instanceMethod();
Foo.classMethod();
Foo b = new Bar();
b.instanceMethod();
Bar.classMethod();
}
}
If you run this, the output is
instanceMethod() in Foo
classMethod() in Foo
instanceMethod() in Bar
classMethod() in Bar
| Is This Answer Correct ? | 3 Yes | 2 No |
Post New Answer View All Answers
What is sortedset in java?
Can a singleton class be inherited?
How can we run a java program without making any object?
Can keyword be used as identifier?
How to invoke external process in java.
Are there structures in java?
What is difference between path and classpath variables?
What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?
What is a memory leak in java?
Why hashcode is used in java?
How many bits is size_t?
What is thread life cycle?
Explain the difference between jdk, jre, and jvm?
In java, how many ways you can take input from the console?
What are the features of java?