Inheritance
Inheritance is similar in Java and C++. Java uses the extends keyword instead of the : token. All inheritance in Java is public inheritance; there is no analog to the C++ features of private and protected inheritance.
Calling base class constructor
In java, we can use super keyword.
super(parameter-list);
eg.
//X is super class, with attributes width, height, depth and has constructor for 3 attributes.
class Y extends X
{
double weight; // weight of box
// initialize width, height, and depth using super()
Y(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
}
2nd use of super in java
The second form of super acts somewhat like this, except that it always refers to
the
superclass of the subclass in which it is used. This usage has the following
general form:
super.member
Here, member can be either a method or an instance variable.
eg.
// Using super to overcome name hiding.
class A {
int i;
}
// Create a subclass by extending class A.
class B extends A {
int i; // this i hides the i in A
B(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);
}
}
Multilevel inheritance - Base class constructor is called 1st.
// Demonstrate when constructors are called.
// Create a super class.
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
C h a p t e r 8 : I n h e r i t a n c e 207
THE JAVA LANGUAGE
C c = new C();
}
}
The output from this program is shown here:
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor