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
Why we use multi threading instead of multiprocessing?
How many bytes is a string?
What are the two ways in which thread can be created?
What is java reflection?
How is hashset defined in java?
How do you implement tree mirroring in java?
What is the method in java?
What is an example of a keyword?
Write a method to check if input string is palindrome?
Is it possible to write a regular expression to check if string is a number?
What modifiers may be used with a top-level class?
What is multi-catch block in java?
What are abstract methods in java?
What is an interface in java? Explain
When a byte datatype is used?