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
.
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.
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.
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.
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.
You can do:
super.alphaMethod1();
Note, that super
is a reference to the parent class, but super()
is its constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With