java non-static to static method — hiding or overriding

拟墨画扇 提交于 2019-12-03 17:05:25

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.

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.

How can you override a method that is final.

The final methods can never be overrided in the subclass.

That is the compilation error..

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
  }
}

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.

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