A general class is created with attributes. Another class can inherit those attributes using concept - Inheritance.

The class that inherits is called subclass and the class that is inherited is called superclass.

Simple Inheritance

Code

  
class A {
int i, j;

void showij() {
System.out.println("i and j: " + i + " " + j);
}
}

class B extends A {
int k;

void showk() {
System.out.println("k: " + k);
}

void sum() {
System.out.println("i + j + k: " + (i + j + k));
}
}

public class SimpleInheritance {
public static void main(String[] args) {
A superOb = new A();
B subOb = new B();

superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();

subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();

System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}

Output:

Contents of superOb: 
i and j: 10 20

Contents of subOb:
i and j: 7 8
k: 9

Sum of i, j and k in subOb:
i + j + k: 24

Member access

A subclass can’t inherit a private object of it’s superclass.

 

class A {
int i;
private int j;

void setij(int x, int y) {
i = x;
j = y;
}
}

class B extends A {
// A's j is not accessible here
int total;

void sum() {
total = i + j; // ERROR, as j is private
}
}

Reference between SuperClass and SubClass Objects

Code:

 

/*
Box(int w, int h, int d);
BoxWeight extends Box {
int m;
}
*/


BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);
Box plainbox = new Box();

plainbox = weightbox; // Acceptable

vol = plainbox.volume(); // volume() is defined in Box

int weight = plainbox.weight(); // Not Acceptable
// Plainbox object doesn't have weight variable.

Using super to call Superclass constructors

Code

 

// BoxWeight now uses super to initialize its Box attributes.

class BoxWeight extends Box {
double weight;
// initialize width, height, and depth using super()

BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
}

Multilevel heirachies & Order of Derivation

Code

 

// 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 c = new C();
}
}

Method Overriding

Subclass methods always overrides the superclass’s methods.
It only occurs if name and type (parameter’s given) is identical else the method is overloaded.