77

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.

Rudra
  • 383
  • 3
  • 17
roz
  • 791
  • 1
  • 5
  • 4
  • 2
    Try super without the parens. – Jacob Aug 01 '11 at 09:32
  • 3
    `super.alphaMethod1()` actually. Why don't you just try and see what happens ;) ? Also, this question has probably been asked hundreds of times already... – Tedil Aug 01 '11 at 09:32
  • 3
    I'm aware this question is now quite old but if you are aware of any duplicates then mark the question as duplicate. This is now the top result on google and well answered! – mattumotu Jan 25 '15 at 11:11

7 Answers7

126

You can do:

super.alphaMethod1();

Note, that super is a reference to the parent class, but super() is its constructor.

Dimitri Hautot
  • 438
  • 5
  • 12
Michał Šrajer
  • 30,364
  • 7
  • 62
  • 85
  • Some call super method at the end or some at the start why? – Asif Mushtaq Jun 28 '17 at 13:23
  • 2
    In constructor, you need to call super() as a first statement (if you call it explicitly). On regular methods you call it wherever you want depending on your app logic needs. For example at the beginning if you want to add extra steps after call or at the end if you add extra check. – Michał Šrajer Jul 01 '17 at 14:00
  • 2
    @MichałŠrajer using `super` you cannot call method from class `alpha` into `Test` class which extends class `beta` – Rudra Apr 08 '18 at 03:11
  • As a Java beginner I just wonder why `super()` does not have the magic to *know* in which method it is being used (Meaning: If `foo()` calls `super()`, it's obvious that `super()` means `super.foo()`. Constructors are just too special in Java IMHO) See `Precursor` in Eiffel, where it's done right. – U. Windl May 24 '18 at 08:02
  • 1
    Additional info: `super.alphaMethod1();` can't be called from `main` method. This answer doesn't state it, but this call needs to be made from somewhere *within* non-static context of subclass: `beta`. – Pshemo May 10 '21 at 14:48
  • @Michal, this is a totally wrong answer. If you use super.alphaMethod1() you get a compiler error saying "cant invoke from static context, make main non-static". How is this answer upvoted?? – abc123 Oct 03 '21 at 06:33
22

Simply use super.alphaMethod1();

See super keyword in java

Sandeep Pathak
  • 10,567
  • 8
  • 45
  • 57
20

You can't call alpha's alphaMethod1() by using beta's object But you have two solutions:

solution 1: call alpha's alphaMethod1() from beta's alphaMethod1()

class Beta extends Alpha
{
  public void alphaMethod1()
  {
    super.alphaMethod1();
  }
}

or from any other method of Beta like:

class Beta extends Alpha
{
  public void foo()
  {
     super.alphaMethod1();
  }
}

class Test extends Beta 
{
   public static void main(String[] args)
   {
      Beta beta = new Beta();
      beta.foo();
   }
}

solution 2: create alpha's object and call alpha's alphaMethod1()

class Test extends Beta
{
   public static void main(String[] args)
   {
      Alpha alpha = new Alpha();
      alpha.alphaMethod1();
   }
}
Vishal Yadav
  • 3,642
  • 3
  • 25
  • 42
CKR666
  • 1,497
  • 1
  • 13
  • 10
5

It is possible to use super to call the method from mother class, but this would mean you probably have a design problem. Maybe B.alphaMethod1() shouldn't override A's method and be called B.betaMethod1().

If it depends on the situation, you can put some code logic like :

public void alphaMethod1(){
    if (something) {
        super.alphaMethod1();
        return;
    }
    // Rest of the code for other situations
}

Like this it will only call A's method when needed and will remain invisible for the class user.

Dalshim
  • 315
  • 2
  • 9
3

Solution is at the end of this answer, but before you read it you should also read what is before it.


What you are trying to do would break security by allowing skipping possible validation mechanisms added in overridden methods.

For now lets imagine we can invoke version of method from superclass via syntax like

referenceVariable.super.methodName(arguments)

If we have classes like

class ItemBox{ //can sore all kind of Items
    public void put(Item item){
        //(1) code responsible for organizing items in box 
    }

    //.. rest of code, like container for Items, etc.
}

class RedItemsBox extends ItemBox {//to store only RED items

    @Override
    public void put(Item item){ //store only RED items
        if (item.getColor()==Color.RED){
            //(2) code responsible for organizing items in box
        }
    }
}

As you see RedItemsBox should only store RED items.

Regardless which of the below we use

ItemBox     box = new RedItemsBox();
RedItemsBox box = new RedItemsBox();

calling

box.put(new BlueItem());

will invoke put method from RedItemsBox (because of polymorphism). So it will correctly prevent BlueItem object from being placed in RedItemBox.

But what would happen if we could use syntax like box.super.put(new BlueItem())?

Here (assuming it would be legal) we would execute version of put method from ItemBox class.
BUT that version doesn't have step responsible for validating Item color. This means that we could put any Item into a RedItemBox.

Existence of such syntax would mean that validation steps added in subclasses could be ignored at any time, making them pointless.


There IS a case where executing code of "original" method would make sense.

And that palce is inside overriding method.

Notice that comments //(1) .. and //(2).. from put method of ItemBox and RedItemBox are quite similar. Actually they represent same action...

So it makes sense to reuse code from "original" method inside overriding method. And that is possible via super.methodName(arguments) call (like from inside put of RedItemBox):

@Override
public void put(Item item){ //store only RED items
    if (item.getColor()==Color.RED){
        super.put(item); // <<<--- invoking code of `put` method 
                         //        from ItemBox (supertype)
    }
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
2

Whenever you create child class object then that object has all the features of parent class. Here Super() is the facilty for accession parent.

If you write super() at that time parents's default constructor is called. same if you write super.

this keyword refers the current object same as super key word facilty for accessing parents.

Pradip Bhatt
  • 668
  • 9
  • 15
0

beta obj = new beta(); Since you have created beta object , you cant refer directly to alphamethod1 of alpha object. It can be modified as

class Beta extends Alpha
{
  public void alphaMethod1()
  {
    super.alphaMethod1();
  }
}
Bhanu
  • 21
  • 5