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’s something inside her and no one else should have access, not even her derivative types.
If the method only exists in it, it cannot be seen or accessed by the derived types, any method that has the same signature is a new method. The superscript would only occur if the method existed for the derivative type. And even then if it were not final
. I imagine you understand that the final
also prevents the envelope.
What you may not know is that it does not prevent an equal signature method. Only in this case the overlap will occur. In most cases it is not what you want.
This is about 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 will be called.
When the method is not virtual, the method that will be called is always the generic type. Polymorphism does not occur. Then you think that the method with the same signature in the derivative type will be called, but it will not be. 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();
}
}
Polymorphism-free:
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 the other publicly. They do not get confused. You can’t override something you can’t even see. If it’s private, the compiler will ignore the method.
No polymorphism but all public
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();
}
}
I put in the Github for future reference.
There is the "virtual" modifier in java?
– user28595
He is the default. He didn’t use anything, it’s virtual.
– Maniero