Call the method of a specific superclass

1

Suppose I have the following hierarchical structure in Java:

First a class Avo :

public class Avo {
    protected String nome;

    public void falar() {
        //Codigo aqui
    }
}

Then I have a class Pai that inherits from Avo and overrides its talk method:

public class Pai extends Avo {
    @Override
    public void falar() {
        //Codigo aqui
    }
}

Finally I have a class Filho that inherits from Pai and once again overrides the talk method:

public class Filho extends Pai{
    @Override
    public void falar() {
        //Chamar método falar da classe Avo

       //Resto da implementação
    }
}

Is there any way in the talk method of class Filho to call the talk method of the superclass Avo instead of the method of the superclass Pai ? I know that in C ++ you can Avo::falar() , is there something similar in Java?

    
asked by anonymous 18.04.2018 / 17:44

2 answers

2

Can not, if you inherit from Pai you have to conform to this class. It is not even a matter of Filho who Pai inherits. If you need to do this, the modeling is probably wrong.

For me C ++ lets you break the encapsulation. I think the mechanism was not even created for this, but rather to access classes horizontally, since it allows multiple inheritance, not vertical.

Maybe what you want is just an interface, eventually with method implemented in it. Most of the inheritances I see here on the site should not be a complete inheritance, establish contracts, or simple reuse does not require and most often can not be through inheritance.

I can not say the correct way because I do not know what the problem is, the question only talks about accessing Grandma's method and this does not. Each problem has a different solution with the appropriate mechanism.

    
18.04.2018 / 17:52
1

If you made the class Pai (maybe yourself) decided to replace the method of class Avo with another, it is because it was inappropriate, incomplete or something.

If, on the other hand, the class Filho wants to reuse the Avo method, then the Pai class simply should not have replaced it.

It's that simple, you replace what you want to delete and play outside the superclass. If you replaced, but did not want to delete or throw away, it's because you should not have replaced it in the first place.

There are several ways to deal with this problem and come up with a different modeling to solve it. However, your example is too artificial for me to suggest a contour that applies to your actual case.

    
18.04.2018 / 18:04