It is not the same if the method is declared as private
. This modifier indicates that the method should only exist within the class. It is something internal to her and no one else should have access, not even the types derived from it.
If the method only exists in it, it can not be seen or accessed by the derived types, any method that has the same signature is a new method. The overwrite would only occur if the method existed for the derived type. And even if it was not final
. I assume you understand that final
also prevents overwriting.
What you may not know is that it does not prevent an identical subscription method. Only in this case will the overlap occur. In most cases it is not what you want.
This has to do with polymorphism.
When the method is public and virtual, where one expects a more generic type can use the more specific type and the method of this type is what will be called.
When the method is not virtual, the method that will be called is always of the generic type. Polymorphism does not occur. Then you think that the method with the same signature in the derived type will be called, but it will not. It can only be called directly.
class A {
public metodo() { System.out.println("A"); }
}
class B extends A {
@override public metodo() { System.out.println("B"); }
}
class Principal {
public static main() {
B x = new B();
teste(x); // imprime B porque B é derivado de A e o método é virtual
A y = new A();
teste(y); // imprime A
}
public static teste(A x) {
x.metodo();
}
}
No polymorphism:
class A {
private metodo() { System.out.println("A"); }
}
class B extends A {
public metodo() { System.out.println("B"); }
}
class Principal {
public static main() {
B x = new B();
testeB(x); //Imprime B
teste(x); //por ser privado, é final, e o compilador não tenta acessar o tipo derivado
// não vai funcionar, teste() só consegue acessar o método de A, que é privado
A y = new A();
teste(y); //não vai funcionar
}
public static teste(A x) {
x.metodo(); //não compila, o método não existe, métodos privados não são acessíveis fora da classe
}
public static testeB(B x) {
x.metodo();
}
}
Note that here the methods have the same signature but one exists privately and another publicly exists. They are not confused. You can not overwrite something you can not even see. If it is private the compiler will ignore the method.
Sem polimorfismo mas tudo público
class A {
final public metodo() { System.out.println("A"); }
}
class B extends A {
public metodo() { System.out.println("B"); }
}
class Principal {
public static main() {
B x = new B();
testeB(x); //Imprime B, óbvio, não tem como errar
teste(x); //Imprime A, não há polimorfismo, ele só entende o que há em A
A y = new A();
teste(y); //imprime A
}
public static teste(A x) {
x.metodo();
}
public static testeB(B x) {
x.metodo();
}
}