java non-static to static method — hiding or overriding

↘锁芯ラ 提交于 2019-12-05 06:20:58

问题


is re-defining a non-static method in a subclass with the same everything but as static overriding or hiding it ?

http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html says hiding. but when i declare the superclass method as final, i get an override error.

superclass declaration is

final static void display() { ... }

subclass:

void display() { ... }

gives override error.


回答1:


Is re-defining a non-static method in a subclass with the same everything but as static overriding or hiding it?

It's neither, because doing so triggers a compilation error, rendering your program invalid.

class A {
    void x();
}
class B extends A {
    // ERROR!!!
    static void x();
}

Hiding happens when both methods in the pair are static methods; overriding happens when both methods in the pair are instance methods. When one of the two is a static method and the other one is an instance method, Java considers it an error. It does not matter if the instance method is final or not; it also does not matter if the static method is in the base or in the derived class: Java calls it an error either way.

The compiler message that says "cannot override" is misleading, though: I think that "name collision" would have been a better name for such conditions, because "overriding" is reserved for situations with two instance methods.




回答2:


The method you describe is an instance method, not a static method. You cannot hide instance methods, only static methods. An instance method declared final cannot be overridden in a subclass, and this is what you are trying to do.




回答3:


How can you override a method that is final.

The final methods can never be overrided in the subclass.

That is the compilation error..




回答4:


You can't override a final method...

Ex:

class Super
{
  final void display()
  {
    //do something
  }

  void show()
  {
    //Do Something
  }
}


class Sub extends Super
{
  //Not Valid hence Compile Error
  void display()
  {
    //do something
  }

  //Valid
  void show()
  {
    //Do Something
  }
}



回答5:


final static void display() { ... }

The above method is having non-access modifier final, and a method which has been made final can't be overridden.



来源:https://stackoverflow.com/questions/13447878/java-non-static-to-static-method-hiding-or-overriding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!