Inheritance Java
Inheritance Java
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
new or modified capabilities.
The existing class is called superclass.
The new class is called subclass.
The subclass exhibit the behaviors of it’s
superclass and additional behaviors that are
specific to the subclass.
Java does not support multiple inheritances
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:
Output:
subOb.k = 9; Contents
ContentsofofsuperOb:
superOb:
System.out.println("Contents of subOb: "); i iand
andj:j:10
1020 20
subOb.showij();
subOb.showk(); Contents
ContentsofofsuperOb:
superOb:
System.out.println(); i iand
andj:j:7788
K:K:99
System.out.println("Sum of i, j and k in subOb:");
subOb.sum(); Sum
SumofofI,I,j,j,kkininsubOb:
subOb:
}
i+j+k:
i+j+k:2424
}
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.
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
depth = ob.depth; created
} Box(double len) {
width = height = depth = len;
// 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:
Output:
weight = m;
} Volume
Volumeofofmybox1
mybox1isis3000.0
3000.0
} Weight
Weightofofmybox1
mybox1isis34.3
34.3
class DemoBoxWeight {
public static void main(String args[]) { Volume
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); Volumeofofmybox2
mybox2isis24.0
24.0
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); Weight
Weightofofmybox2
mybox2isis0.076
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);
}
}
A superclass variable can
Reference a subclass object
class RefDemo {
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
Volumeofofweightbox
weightboxisis105.0
105.0
plainbox = weightbox; Weight
Weightofofweightbox
weightboxisis8.37
8.37
vol = plainbox.volume(); // OK, volume() defined in Box
System.out.println("Volume of plainbox is " + vol); Volume
Volumeofofplainbox
plainboxisis105.0
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.
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);
Parameter-list specifies any parameters needed by the
constructor in the superclass.
Super must be first statement execute inside a
subclass’ constructor
A complete version of BoxWeight
// A complete implementation of BoxWeight. // constructor used when no dimensions
class Box { specified
private double width; Box() {
private double height; width = -1; // use -1 to indicate
private double depth; height = -1; // an uninitialized
depth = -1; // box
// construct clone of an object
}
Box(Box ob) { // pass object to constructor
width = ob.width;
// constructor used when cube is created
height = ob.height;
Box(double len) {
depth = ob.depth;
width = height = depth = len;
}
}
// 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; }
} }
// BoxWeight now fully implements all constructors.
class BoxWeight extends Box {
double weight; // weight of box
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();
}
}
Output:
// construct clone of an object
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).
Box
BoxWeight
Shipment
// Add weight.
class BoxWeight extends Box { // default constructor
double weight; // weight of box BoxWeight() {
super();
// construct clone of an object
weight = -1;
BoxWeight(BoxWeight ob) { //
pass object to constructor }
super(ob);
weight = ob.weight; // constructor used when cube is
} created
BoxWeight(double len, double m)
// constructor when all parameters {
are specified super(len);
BoxWeight(double w, double h, weight = m;
double d, double m) {
}
super(w, h, d); // call superclass
constructor }
weight = m;
}
// Add shipping costs // default constructor
class Shipment extends BoxWeight {
Shipment() {
double cost;
super();
// construct clone of an object
cost = -1;
Shipment(Shipment ob) { // pass object }
to constructor
super(ob); // constructor used when cube is
cost = ob.cost; created
} Shipment(double len, double m,
double c) {
// constructor when all parameters are super(len, m);
specified
cost = c;
Shipment(double w, double h, double
d, double m, double c) { }
super(w, h, d, m); // call superclass }
constructor
cost = c;
}
class DemoShipment {
public static void main(String args[]) {
Shipment shipment1 = new Shipment(10, 20, 15, 10, 3.41);
Shipment shipment2 = new Shipment(2, 3, 4, 0.76, 1.28);
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 Iand
andj:j:1122
super.show(); // this calls A's show()
K:
K:33
System.out.println("k: " + k);
}
}
A practical example
Mobile
SmartPhone
void receiveMessage(String message, String
number)
void sendGpsPosition(String number)
A superclass variable can
Reference a subclass object
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
InsideA’s
A’scallme
callmemethod
method
B b = new B(); // object of type B
C c = new C(); // object of type C Inside
InsideB’s
B’scallme
callmemethod
method
A r; // obtain a reference of type A Inside
InsideC’s
C’scallme
callmemethod
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.
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
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
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!");
}
}