Pergunta

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.

Foi útil?

Solução

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.

Outras dicas

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.

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.

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
  }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top