Java Inheritance - calling superclass method

roz picture roz · Aug 1, 2011 · Viewed 153.3k times · Source

Lets suppose I have the following two classes

public class alpha {

    public alpha(){
        //some logic
    }

    public void alphaMethod1(){
        //some logic
    }
}

public class beta extends alpha {

    public beta(){
        //some logic
    }

    public void alphaMethod1(){
        //some logic
    }
}

public class Test extends beta
{
     public static void main(String[] args)
      {
        beta obj = new beta();
        obj.alphaMethod1();// Here I want to call the method from class alpha.
       }
}

If I initiate a new object of type beta, how can I execute the alphamethod1 logic found in class alpha rather than beta? Can I just use super().alphaMethod1() <- I wonder if this is possible.

Autotype in Eclipse IDE is giving me the option to select alphamethod1 either from class alpha or class beta.

Answer

Michał Šrajer picture Michał Šrajer · Aug 1, 2011

You can do:

super.alphaMethod1();

Note, that super is a reference to the parent, but super() is it's constructor.