Calling the method of a specific superclass

Asked

Viewed 165 times

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
    }
}

Next I have a class Pai who inherits from Avo and overwritten his method of speaking:

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

I finally have a class Filho who inherits from Pai and once again overrides the method to speak:

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 method to speak of the class Filho call the method speak of the superclass Avo instead of the superclass method Pai? I know in C++ can do Avo::falar(), has something similar in Java?

2 answers

2


Can’t if you inherited from Pai has to conform to this class. Nor is it a problem of Filho whosoever Pai inherits. If you need to do this, the modeling is probably wrong.

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

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

I can’t say the right way because I don’t know what the problem is, the question only talks about accessing the grandmother’s method and this doesn’t work. Each problem has a different solution with the proper mechanism.

  • Se está precisando fazer isto, a modelagem provavelmente está errada. - that was the first sentence that came to mind after reading the question.

  • Thank you very much, I’ll fix my modeling.

1

If who made the class Pai (maybe yourself) decided to replace the class method Avo by one another, it is because he was inadequate, incomplete or something.

If on the other hand, the class Filho or re-use the Avo, then the class Pai I just shouldn’t have replaced him.

It’s that simple, you replace what you want to erase and throw out of the superclass. If you replaced it, but didn’t want to erase it or throw it away, it’s because you shouldn’t 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 an outline that applies to your actual case.

Browser other questions tagged

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