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 the differences between c++ and java? Explain
What is the public method modifier?
what is method reference in java 8?
What things should be kept in mind while creating your own exceptions in java?
Give us a program to check for parenthesis matching using stack.
What do you mean by chromounits in java8?
What is append in java?
Can we serialize arraylist in java?
Why do we override tostring method in java?
How many JVMs can run on a single machine and what is the Just-In-Time(JIT) compiler?
Which method cannot be overridden in java?
Is treeset sorted in java?
What is the difference between Grid and Gridbaglayout?
Define locale.
What do you understand by the bean persistent property?