Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static method in the subclass that has the same signature as the one in the superclass [closed]

"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.

like image 258
Rushikesh Garadade Avatar asked Mar 19 '23 18:03

Rushikesh Garadade


2 Answers

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.

like image 164
Nathan Hughes Avatar answered Apr 26 '23 14:04

Nathan Hughes


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");
  }
}
like image 42
Elliott Frisch Avatar answered Apr 26 '23 14:04

Elliott Frisch