Inheritance Basics
To inherit a class, you can use the extends
keyword.
The following program creates a superclass called Base
and a subclass called Child
.
class Base {
int i, j;
void showBase() {
System.out.println("i and j: " + i + " " + j);
}
}
class Child extends Base {
int k;
void showChild() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i + j + k));
}
}
public class Main {
public static void main(String args[]) {
Base superOb = new Base();
Child subOb = new Child();
superOb.i = 10;
superOb.showBase();
System.out.println();
subOb.i = 7;
subOb.showBase();
subOb.showChild();
System.out.println();
subOb.sum();
}
}
The output from this program is shown here:
i and j: 10 0
i and j: 7 0
k: 0
i+j+k: 7
The subclass Child
includes all of the members of its superclass
The general form of a class declaration that inherits a superclass is shown here:
class subclass-name extends superclass-name {
// body of class
}
You can only have one superclass for any subclass.
Java does not support the multiple inheritance. A class can be a superclass of itself.
A Superclass Variable Can Reference a Subclass Object
For example, consider the following:
class Rectangle {}
class ColorRectangle extends Rectangle {}
public class Main {
public static void main(String args[]) {
Rectangle rectangle = new Rectangle();
ColorRectangle colorRectangle = new ColorRectangle();
rectangle = colorRectangle;
}
}