1

There are three classes - Children, Father, and Ancestor. Children extends Father, and Father extends Ancestor, like below:

public class Ancestor {
    public void test() {
    }
}

public class Father extends Ancestor {
    @Override
    public void test() {
    }
}

public class Children extends Father {
    @Override
    public void test() {
    }
}

How I can use Ancestor's test() method in Children's test() method? I want to skip Father's test() method.

Makoto
  • 104,088
  • 27
  • 192
  • 230
bitristan
  • 631
  • 8
  • 16

2 Answers2

1

You can't. Java does not permit doing something like super.super.method(). The reasons for this are outlined in this excellent answer, but the bottom line is that it violates encapsulation.

If the functionality is really necessary, and it makes sense to do something like this, you can always add a method in your Father class that just calls the super.test() method, but doing things like this is usually bad practice. Unless you have some really good reasoning, rethink your code. There shouldn't really be any necessity to call a method from either this nor super.

Community
  • 1
  • 1
Alexis King
  • 43,109
  • 15
  • 131
  • 205
0

The short answer is, you can't. It violates encapsulation and is generally bad practice. A better way to accomplish what you want would be to make Ancestor.test() abstract and have a new protected method like Ancestor.baseTest(); Then, you could call Ancestor.baseTest() from Father, Child and any other subclass that wants to access the logic.

Steven Mastandrea
  • 2,752
  • 20
  • 26
  • My only problem with this is that it really *shouldn't* be necessary in most cases. By proposing that such a solution is a perfectly valid one, you may leave the false impression that this is an okay thing to do. Really, you should stay away from things like this. – Alexis King Jun 25 '12 at 04:06
  • I agree it shouldn't be necessary in most cases. However, the question didn't give enough context to make a recommendation. If it really is necessary, its better to give the option, IMHO. – Steven Mastandrea Jun 25 '12 at 04:24
  • I guess that's true, but while my answer *did* give the option, it also precautioned against using such methods unless absolutely necessary. Just saying. – Alexis King Jun 25 '12 at 04:25