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


Please Help Members By Posting Answers For Below Questions

Why we use multi threading instead of multiprocessing?

579


How many bytes is a string?

570


What are the two ways in which thread can be created?

604


What is java reflection?

541


How is hashset defined in java?

521






How do you implement tree mirroring in java?

597


What is the method in java?

604


What is an example of a keyword?

550


Write a method to check if input string is palindrome?

586


Is it possible to write a regular expression to check if string is a number?

550


What modifiers may be used with a top-level class?

578


What is multi-catch block in java?

622


What are abstract methods in java?

658


What is an interface in java? Explain

580


When a byte datatype is used?

571