How to use super keyword to reference methods and variables from parent classes in Java
Description
You can use super
in a subclass to refer to its immediate superclass.
super
has two general forms.
- The first calls the superclass' constructor.
- The second is used to access a member of the superclass.
Call superclass constructors
To call a constructor from its superclass:
super(parameter-list);
parameter-list
is defined by the constructor in the superclass.super(parameter-list)
must be the first statement executed inside a subclass' constructor.
Here is a demo for how to use super to call constructor from parent class.
class Box {/*ww w . j a va2 s . c o m*/
private double width;
private double height;
private double depth;
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
double volume() {
return width * height * depth;
}
}
class BoxWeight extends Box {
double weight; // weight of box
BoxWeight(Box ob) { // pass object to constructor
super(ob);
}
}
public class Main {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
BoxWeight myclone = new BoxWeight(mybox1);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
}
}
This program generates the following output:
Volume of mybox1 is 3000.0
Reference members from parent class
We can reference member variable from parent class with super keyword. Its general form is:
super.member
member
can be either a method or an instance variable.
Let's look at the following code.
class Base {/* w ww .j a v a 2s . c o m*/
int i;
}
class SubClass extends Base {
int i; // this i hides the i in A
SubClass(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
public class Main {
public static void main(String args[]) {
SubClass subOb = new SubClass(1, 2);
subOb.show();
}
}
This program displays the following: