Super can be used to refer to any inherited method or instance variable. Just like this, super is only needed if there is another variable or method with the same name.
class A {
protected int one;
public A (int a) {
one = a;
}
public void hi() {
System.out.println ("Hi " + one);
}
}
class B extends A {
protected int two;
public B (int a, int b) {
super (a);
two = b;
}
public void hello() {
super.hi();
System.out.println("Hello " + one + " " + two);
}
}
class C extends B {
protected int three;
public C (int a, int b, int c) {
super (a, b);
three = c;
}
public void salut() {
super.hi();
super.hello();
System.out.println ("Salut " + super.one + " " + super.two + " " + three);
}
}
public class Tester {
public static void main (String[] args) {
C c = new C (5, 6, 7);
c.salut();
}
}
Output - methods & instance variables
Hi 5
Hi 5
Hello 5 6
Salut 5 6 7
Super - constructors
Any class that extends another class must call the constructor of the
other class (using super) from its constructor. The only time that super
is not needed is if the class being extended has the default constructor
(no constructor explicitly written or its constructor has no
parameters). In this case, the constructor calls super() by default.
All classes above it in the hierarchy must also contain the default
constructor in order for this to work.
class A {
protected int one;
public A () {
one = 55;
}
public A (int a) {
one = a;
}
public void hi() {
System.out.println ("Hi " + one);
}
}
class B extends A {
protected int two;
public void hello () {
System.out.println ("Hello");
}
}
class C extends B {
protected int three;
public C (int a, int c) {
three = c;
}
public void salut() {
super.hi();
super.hello();
System.out.println
("Salut " + one + " " two + " " + three);
}
}
public class Tester {
public static void main (String[] args) {
C c = new C (5, 7);
c.salut();
}
}
Output - constructors
Hi 55
Hello
Salut 55 0 7