"You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it." This is sentence which I read from Oracles authorised site for java tutorial.
I tried to implement above concept in this way:
Parent Class:
public class E {
public void throw1()
{
System.out.println("E is throwing");
}
}
Child Class:
public class D extends E{
public static void throw1()
{
System.out.println("D is throwing");
}
}
But I am getting an error saying "This static method cannot hide the instance method from E"
Q1. Am i implemented the concept correctly?
Q2. If yes.. what is problem in it(Why his error occured)? If No... Still what is problem in it?
Q3. If my implementation is wrong for given concept...please give any example which will prove the statement.
The method in the super class is not static, so you can't hide it with a static method. If you make the method in the superclass static then the superclass static method will be hidden.
The fixed example would be
public class E {
public static void foo() {
System.out.println("E");
}
public static void main(String[] args) {
D.foo();
}
}
class D extends E {
public static void foo() {
System.out.println("D");
}
}
which prints D.
This isn't hiding much of anything because I still need a reference to the class to call the method. If I create another class C extends D
but don't add any static methods, then C.foo() will call D.foo, hiding E.foo. In this case the jvm finds the method foo and looks for it starting in C, then proceeding up through the hierarchy until it finds a match.
For method hiding you need both to be static or both to be non-static. You cannot mix and match (if the method is inherited by the sub-class). If E.throw1()
was private then your existing code would work. Alternatively, you can make D.throw1()
not-static and your existing code would work. Finally, you could make E.throw1()
static and your code would work.
public class E {
public static void throw1()
{
System.out.println("E is throwing");
}
}
or
public class E {
private void throw1()
{
System.out.println("E is throwing");
}
}
or
public class D extends E{
public void throw1()
{
System.out.println("D is throwing");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With