Reputation: 760
I have two Java classes: B, which extends another class A, as follows :
class A {
public void myMethod() { /* ... */ }
}
class B extends A {
public void myMethod() { /* Another code */ }
}
I would like to call the A.myMethod()
from B.myMethod()
. I am coming from the C++ world, and I don't know how to do this basic thing in Java.
Upvotes: 152
Views: 291899
Reputation: 1
// Using super keyword access parent class variable
class test {
int is,xs;
test(int i,int x) {
is=i;
xs=x;
System.out.println("super class:");
}
}
class demo extends test {
int z;
demo(int i,int x,int y) {
super(i,x);
z=y;
System.out.println("re:"+is);
System.out.println("re:"+xs);
System.out.println("re:"+z);
}
}
class free{
public static void main(String ar[]){
demo d=new demo(4,5,6);
}
}
Upvotes: 2
Reputation:
super.MyMethod()
should be called inside the MyMethod()
of the class B
. So it should be as follows
class A {
public void myMethod() { /* ... */ }
}
class B extends A {
public void myMethod() {
super.MyMethod();
/* Another code */
}
}
Upvotes: 21
Reputation: 24262
Just call it using super.
public void myMethod()
{
// B stuff
super.myMethod();
// B stuff
}
Upvotes: 146
Reputation: 143
See, here you are overriding one of the method of the base class hence if you like to call base class method from inherited class then you have to use super keyword in the same method of the inherited class.
Upvotes: 3
Reputation: 21
If u r using these methods for initialization then use constructors of class A and pass super keyword inside the constructor of class B.
Or if you want to call a method of super class from the subclass method then you have to use super keyword inside the subclass method like : super.myMethod();
Upvotes: 1
Reputation: 1
I am pretty sure that you can do it using Java Reflection mechanism. It is not as straightforward as using super but it gives you more power.
class A
{
public void myMethod()
{ /* ... */ }
}
class B extends A
{
public void myMethod()
{
super.myMethod(); // calling parent method
}
}
Upvotes: 7
Reputation: 1
class test
{
void message()
{
System.out.println("super class");
}
}
class demo extends test
{
int z;
demo(int y)
{
super.message();
z=y;
System.out.println("re:"+z);
}
}
class free{
public static void main(String ar[]){
demo d=new demo(6);
}
}
Upvotes: 3
Reputation: 11
Answer is as follows:
super.Mymethod();
super(); // calls base class Superclass constructor.
super(parameter list); // calls base class parameterized constructor.
super.method(); // calls base class method.
Upvotes: 20
Reputation: 3251
super.baseMethod(params);
call the base methods with super keyword and pass the respective params.
Upvotes: 4
Reputation: 399773
The keyword you're looking for is super
. See this guide, for instance.
Upvotes: 153