Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Inheritance - calling superclass method

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.

like image 567
roz Avatar asked Aug 01 '11 09:08

roz


People also ask

How do you call a superclass method in Java?

Use of super() to access superclass constructor To explicitly call the superclass constructor from the subclass constructor, we use super() . It's a special form of the super keyword. super() can be used only inside the subclass constructor and must be the first statement.

What does calling the super () method do?

Definition and Usage It is used to call superclass methods, and to access the superclass constructor. The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.

When implementing inheritance in Java what keyword can be used to call methods in the super class?

Use Java's extends keyword to derive a child class from a parent class, invoke parent class constructors and methods, override methods, and more. Java supports class reuse through inheritance and composition. This two-part tutorial teaches you how to use inheritance in your Java programs.

Can we call super in method?

Private methods of the super-class cannot be called. Only public and protected methods can be called by the super keyword. It is also used by class constructors to invoke constructors of its parent class. Super keyword are not used in static Method.


1 Answers

You can do:

super.alphaMethod1(); 

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

like image 97
Michał Šrajer Avatar answered Oct 22 '22 02:10

Michał Šrajer