0

Possible Duplicate:
Why is super.super.method(); not allowed in Java?

This is my code.. Suppose I have three class like

public class ExtendsCheck {
    public void move() {
        System.out.println("M in Extends Check");
    }
}

public class ExtendsCheck2 extends ExtendsCheck{
    public void move() {
        System.out.println("M in Extends Check 2");
    }
}

public class ExtendsCheck3 extends ExtendsCheck2{
    public static void main(String[] args)
    {
        ExtendsCheck3 e3 = new ExtendsCheck3();
        e3.move();
    }   
}

When i called e3.move(), the method move() from ExtendsCheck2 gets called.

My question is what do i have to do, if i want to call the move() of ExtendsCheck class.

Community
  • 1
  • 1
Narendra Pal
  • 6,474
  • 13
  • 49
  • 85

3 Answers3

0

To call parent method use super keyword in inherited methods.

For instance for class ExtendsCheck2 the method:

public void move() {
     super.move();
     System.out.println("M in Extends Check 2");

}

will display:

M in Extends Check
M in Extends Check 2

In case you want to invoke move() of ExtendsCheck class from the ExtendsCheck3 class directly, then reconsider your inheritance architecture. If you need to write such code, then there's an error in architecture of your classes.

0

Within a class you can use parent.move();.

However, there is no such thing as parent.parent.move();. The reason is that this will break when the parent class is refactored, and e.g. an abstract class is inserted, thus increasing the depth of the hierarchy.

Most likely, when you "need" parent.parent.method(), something in your inheritance design is broken because you seem to need to undo something of your parent class.

If this is really sensible, you can always have the parent class offer a "bypass" function, e.g.

@Deprecated
protected void originalMove() {
    super.move();
}

Which ties the move operation again to a well-defined parent class. Note that I do not recommend using this. Most likely, something in your design is broken. For example, you might want to use an abstract class somewhere.

Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194
-2

Simplest way to deal with is :

Extends E = new Extends();
E.move();

or

super.move(); // as the first statement...
AnkitChhajed
  • 415
  • 2
  • 6
  • 9