Difference between private and final methods

Asked

Viewed 1,643 times

15

Studying methods and final classes in Deitel’s book "How to program in Java 6 ed." I came across the following proposition:

The declared private methods are implicitly final because it is impossible to overwrite them in a subclass (although the subclass may declare a new method with the same signature as the private method in the superclass).

I did not understand this last part in italics. Declaring a method with the same signature is not the same as overwriting?

5 answers

15

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.

  • 1

    There is the "virtual" modifier in java?

  • 1

    He is the default. He didn’t use anything, it’s virtual.

11

The keyword final means that the method defined with it cannot be overwritten in a subclass.

Private methods are only accessible within the defined class, so it is not possible to access/overwrite a method private in a subclass.

Declaring a method with the same signature is not the same as overwrite?

This depends on where the method is declared.

When there are two or more methods with the same signatures (parameters of different types) in the same class this is called overload or overloading.

When a method has an equal signature and is inherited from a super class it is called a superscript or override that is, the subclass can change/overwrite the behavior/implementation of the method provided by the super class, of course, provided that this method has not been marked as final.

8

Declaring a method with the same signature is not the same as overwriting?

If you declare methods with the same signature but in completely different classes, this is not overwriting, it is just two methods with the same signature, but that have no relation to each other.

The superscript can only occur in an inheritance or extension relationship between classes and interfaces, i.e., a class can override a superclass method or the interface it implements, provided that this method is visible to the subclass, otherwise it is the same as saying that there are two methods with the signature table that do not relate, as the example of the distinct classes.

6


I’ll be direct,

(although the subclass may declare a new method with the same signature of the private method in the superclass)

I did not understand this last part in italics. Declaring a method with the same signature is not the same as overwriting?

No, because within the super class the calls of private methods, which are made within the superclass will still continue pointing to the method private of the super class itself, even if there is an equal in the subclass.

Super Class

public class SuperClasse {
    public int processar(int x, int y){
         return somar(x,y);
     }

     private int somar(int x, int y){
          return x+y;
     }
}

Classe Filha

public class SubClasse extends SuperClasse {
    private int somar(int x, int y){
         return x*y;
     }
}

Main

public static void main(String[] args) {
    SubClasse sub = new SubClasse();
    int resultado = sub.processar(10, 5);
    System.out.println(resultado+"");
}

Take the test and see the exit.

How do we deduce that there was no overwriting? because if there was overwriting the result would be 50. As there was, the processing made the sum. Want to know how to over write? turn the sum methods into public. Turn and see the result again.

3

Private indicates that the property or method is not inherited by the child classes and only the proprietary class can access the property or method.

Final indicates that the child class can inherit and access (access inherited properties and methods, not parent class properties or methods), but cannot modify or overwrite. That’s all.

What goes beyond this is purely didactic.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.