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 void data type?
What is difference between wait and notify in java?
Explain about class in java?
What do you understand by java virtual machine?
What is the difference between preemptive scheduling and time slicing in java programming?
What are the methods of object class ?
What is a website container?
What is the difference between static class and normal class?
Can a abstract class be defined without any abstract methods?
What do you mean by formatting?
Difference between association, composition and aggregation?
What are three types of loops in java?
Can private members of a base class are inheritable justify?
Is zero a positive integer?
How many types of literals are there in JAVA?