3.1 Inheritance
3.1 Inheritance
Inheritance Basics
A form of software reuse in which a new
class is created by absorbing an existing
class’s members and embellishing them with
decorate/adorn/equip
new or modified capabilities.
The existing class is called superclass.aka parent class
The new class is called subclass. aka child class
The subclass exhibit the behaviors of it’s
superclass and additional behaviors that are
specific to the subclass.
Java does not support multiple inheritances
Multiple Inheritance => A single child class has Multiple parent class
Keyword extend is used.
// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of its superclass. */
subOb.i = 7;
subOb.j = 8; Output:
subOb.k = 9; Contents of superOb:
System.out.println("Contents of subOb: "); i and j: 10 20
subOb.showij();
subOb.showk(); Contents of superOb:
System.out.println(); i and j: 7 8
K: 9
System.out.println("Sum of i, j and k in subOb:");
subOb.sum(); Sum of I, j, k in subOb:
} i+j+k: 24
}
Note that
◼ The subclass B includes all of the members of its
superclass A.
◼ subOb can access i and j and showij().
◼ Inside sum(), i and j can be referred directly.
obvious, as sum() is inside the subclass which can access i j
A member of superclass which is declared as
private can be only accessed by the
superclass not by the outside of the class,
including subclass.
A Practical Example
//This program uses inheritance to extend Box.
class Box { // constructor used when no dimensions
double width; specified
double height; Box() {
double depth; width = -1; // use -1 to indicate
height = -1; // an uninitialized
// construct clone of an object depth = -1; // box
Box(Box ob) { // pass object to constructor }
width = ob.width;
height = ob.height; // constructor used when cube is
created
depth = ob.depth;
Box(double len) {
}
width = height = depth = len;
constructor cloning by using copy constructor }
// constructor used when all dimensions
specified
Box(double w, double h, double d) { // compute and return volume
width = w; double volume() {
height = h; return width * height * depth;
depth = d; }
} }
// Here, Box is extened to include weight.
class BoxWeight extends Box {
double weight; // weight of box
// constructor for BoxWeight
BoxWeight(double w, double h, double d, double m) {
width = w;
height = h;
depth = d; Output:
weight = m;
} Volume of mybox1 is 3000.0
} Weight of mybox1 is 34.3
class DemoBoxWeight {
public static void main(String args[]) { Volume of mybox2 is 24.0
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); Weight of mybox2 is 0.076
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
}
}
object
A superclass variable can
Reference
get it's value from
a subclass object
class RefDemo {
But the opposite is not possible
public static void main(String args[]) {
BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);
Box plainbox = new Box();
double vol;
vol = weightbox.volume();
System.out.println("Volume of weightbox is " + vol);
System.out.println("Weight of weightbox is " + weightbox.weight);
System.out.println();
// assign BoxWeight reference to Box reference Volume of weightbox is 105.0
plainbox = weightbox; Weight of weightbox is 8.37
vol = plainbox.volume(); // OK, volume() defined in Box
System.out.println("Volume of plainbox is " + vol); Volume of plainbox is 105.0
/* The following statement is invalid because plainbox
does not define a weight member. */
// System.out.println("Weight of plainbox is " + plainbox.weight);
}
}
It is the type of the reference variable – not
the type of the object that it refers to – that
determines what members can be accessed.
When a reference to a subclass object is
assigned to a superclass reference variable:
◼ You have access only to those parts of the object
defined by the superclasss.
That doesn't mean if you crate a class with two int variables and another class of different name with two int
variables of same name; you can copy them. An object of a particular class can only be copied to an object of the
same class, or it's superclass
Super Keyword
Refer to immediate superclass.
Have two general form:
◼ Call superclass’ constructor.
◼ Access the member of the superclass that has
been hidden by a member of a subclass.
Using super to call Superclass constructor
◼ super(parameter-list); Must use super, can't write this.variablename=variablename
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
System.out.println();
vol = mybox3.volume();
System.out.println("Volume of mybox3 is " + vol);
System.out.println("Weight of mybox3 is " + mybox3.weight);
System.out.println();
vol = myclone.volume();
System.out.println("Volume of myclone is " + vol);
System.out.println("Weight of myclone is " + myclone.weight);
System.out.println();
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
System.out.println("Weight of mycube is " + mycube.weight);
System.out.println();
}
}
// construct clone of an object
Output:
Volume of mybox1 is 3000.0 BoxWeight(BoxWeight ob) { // pass object to
Weight of mybox1 is 34.3 constructor
super(ob);
Volume of mybox2 is 24.0
Weight of mybox2 is 0.076 weight = ob.weight;
}
Volume of mybox3 is -1.0 ✓ super is called with an object of
Weight of mybox3 is -1.0 BoxWeight – not of type Box.
Volume of myclone is 3000.0 ✓Still invoke the constructor of
Weight of myclone is 34.3 Box(Box ob).
double vol;
vol = shipment1.volume();
System.out.println("Volume of shipment1 is " + vol);
System.out.println("Weight of shipment1 is "
+ shipment1.weight);
System.out.println("Shipping cost: $" + shipment1.cost);
System.out.println();
vol = shipment2.volume();
System.out.println("Volume of shipment2 is " + vol);
System.out.println("Weight of shipment2 is "
+ shipment2.weight);
System.out.println("Shipping cost: $" + shipment2.cost);
}
}
Method Overriding
void show() {
I and j: 1 2
super.show(); // this calls A's show()
K: 3
System.out.println("k: " + k);
}
}
A practical example
Mobile
SmartPhone
void receiveMessage(String message, String number)
void sendGpsPosition(String number)
See .docx note for this topic and DMD
A superclass variable can
Reference a subclass object
aka Upcasting
Table t;
t = new Chair();
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
Inside A’s callme method
B b = new B(); // object of type B
C c = new C(); // object of type C Inside B’s callme method
A r; // obtain a reference of type A Inside C’s callme method
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
figref = t;
System.out.println("Area is " + figref.area());
figref = f;
System.out.println("Area is " + figref.area());
}
}
Dynamic Method dispatch
Bank
BracBank
OneBank
Abstract Classes
Define a superclass that declares the structure of a
given abstraction without providing a complete
implementation of every methods.
Want to create a superclass that only defines a
generalized form that will be shared by all of it’s
subclasses, leaving it to each subclass to fill in the
details. make it mandatory for
You can require that certain methods be overridden
by the subclasses by specifying the abstract type
modifier.
◼ A subclass must override the abstract methods
General form:
◼ Abstract type name(parameter_list);
Any class that contain one or more abstract
method
class must be declared as abstract.
◼ There is no object of an abstract class, because:
⚫ Abstract class is not fully defined.
⚫ Any subclass of an abstract class must implement all
of the abstract methods in the superclass or be itself
declare as abstract.
◼ But it is possible to create reference of an
abstract class.
// Using abstract methods and classes.
abstract class Figure { class Triangle extends Figure {
double dim1; First abstract then class Triangle(double a, double b) {
double dim2;
super(a, b);
Figure(double a, double b) { }
dim1 = a;
dim2 = b;
}
// override area for right triangle
// area is now an an abstract method double area() {
abstract double area();
} System.out.println("Inside Area for Triangle.");
First abstract then return type
class Rectangle extends Figure { return dim1 * dim2 / 2;
Rectangle(double a, double b) { }
super(a, b);
} }
figref = r;
System.out.println("Area is " + figref.area()); It can used to
refer any object
figref = t; derive form
System.out.println("Area is " + figref.area()); Figure.
}
}
Use final to prevent Overriding
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}