0% found this document useful (0 votes)
30 views

Inheritance Java

Inheritance allows a subclass to inherit attributes and behaviors from a superclass. The subclass extends the superclass and can define additional attributes and behaviors. Java does not support multiple inheritance, but a subclass can inherit from only one superclass using the extend keyword. A superclass reference can refer to a subclass object, but it only has access to attributes and behaviors defined in the superclass. The super keyword can be used to call the superclass constructor or access attributes hidden by the subclass.

Uploaded by

NAFISA SHAMS
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Inheritance Java

Inheritance allows a subclass to inherit attributes and behaviors from a superclass. The subclass extends the superclass and can define additional attributes and behaviors. Java does not support multiple inheritance, but a subclass can inherit from only one superclass using the extend keyword. A superclass reference can refer to a subclass object, but it only has access to attributes and behaviors defined in the superclass. The super keyword can be used to call the superclass constructor or access attributes hidden by the subclass.

Uploaded by

NAFISA SHAMS
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 42

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
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);
}
}

// Create a subclass by extending class A.


class B extends A {
int k;

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

// construct clone of an object


BoxWeight(BoxWeight ob) { // pass object to constructor
super(ob);
weight = ob.weight;
}

// constructor when all parameters are specified


BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
} // constructor used when cube is
created
// default constructor BoxWeight(double len, double m) {
BoxWeight() { super(len);
super(); weight = m;
weight = -1; }
} }
class DemoSuper {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
BoxWeight mybox3 = new BoxWeight(); // default
BoxWeight mycube = new BoxWeight(3, 2);
BoxWeight myclone = new BoxWeight(mybox1);
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);
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).

Volume of mycube is 27.0


 A superclass variable can be used to
Weight of mycube is 2.0 reference any object derived from that
class.
Second use of super

 Act somewhat like this except that it is


always refer to the superclass of the subclass.
 Super.member
class A
{ class SuperTest
int i,j; {
A(int a, int b) public static void main(String args[])
{
{
i=a;
B ob1=new B(1,2,3);
j=b;
}
ob1.show();
} }
}
class B extends A
{
int i;
B(int a,int b,int c)
{
super(a,b);
i=c;
}
void show() i iofofclass
classBB33
{ i iofofclass
classAA11
System.out.println("i of class B "+i);
j jofofclass
classAA22
System.out.println("i of class A "+super.i);
System.out.println("j of class A "+j);
}
}
Multilevel Hierarchy
// Start with Box. // constructor used when no
class Box { dimensions 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 lone of an object }
Box(Box ob) { // pass object to constructor
width = ob.width; // constructor used when cube is
height = ob.height; created
depth = ob.depth; Box(double len) {
} width = height = depth = len;
}
// constructor used when all dimensions
specified
// compute and return volume
Box(double w, double h, double d) {
double volume() {
width = w;
return width * height * depth;
height = h;
depth = d; }
} }
Multilevel Hierarchy

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

 When a method in a subclass has the same


name and type signature a method in its
superclass, the method is in subclass is said
to override the method in the superclass.
 When a override method is called from
within a subclass
 It always call the override method of subclass.
// Method overriding.
// display k -- this overrides show() in
class A { A
int i, j; void show() {
System.out.println("k: " + k);
A(int a, int b) { }
i = a; }
j = b;
} class Override {
// display i and j public static void main(String
args[]) {
void show() {
B subOb = new B(1, 2, 3);
System.out.println("i and j: " + i + " " + j);
}
subOb.show(); // this calls show()
}
in B
class B extends A { }
int k; }

B(int a, int b, int c) { K:


K:33
super(a, b);
k = c;
}
 Using super you can call superclass’ override
method.
class B extends A {
int k;

B(int a, int b, int c) {


super(a, b);
k = c;
}

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

void makeACall(String number)


void receiveACall(String number)
void receiveMessage(String message, String number)

SmartPhone
void receiveMessage(String message, String
number)
void sendGpsPosition(String number)
A superclass variable can
Reference a subclass object
 Table t;
 t = new Chair();

 Car c = new Book();


Vehicle
 Vehicle v; void drive();
 Car c = new car();
 ElectricCar ec = new ElectricCar();
 v = c; Car
 v.drive(); void drive();
 v.givingTurnSignal(); void givingTurnSignal()
 v = ec;
 v.displayInfo();
ElectricCar
void drive();
void displayInfo();
Dynamic Method Dispatch
 By which a call to an overridden function is resolve
at run time, rather than compile time.
 Using this, java implements run time
polymorphism.
 A superclass reference variable can refer to a
subclass object.
 When an overridden method is called through a
superclass reference
 Java determines which version of that method to execute
based upon the type of the object being referred to at the
time the call occur.
// Dynamic Method Dispatch
class A {
void callme() {
System.out.println("Inside A's callme method");
}
}

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
}
}

It allows a general class to specify methods that will be common to all of


it’s derivatives, while allowing subclass to define the specific
implementation of some or all of those methods.
// Using run-time polymorphism.
class Figure {
double dim1; class Triangle extends Figure {
double dim2; Triangle(double a, double b) {
Figure(double a, double b) { super(a, b);
dim1 = a;
}
dim2 = b;
}
double area() { // override area for right triangle
System.out.println("Area for Figure is undefined.");
double area() {
return 0;
} System.out.println("Inside Area for
} Triangle.");

class Rectangle extends Figure { return dim1 * dim2 / 2;


Rectangle(double a, double b) { }
super(a, b);
}
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class FindAreas {
public static void main(String args[]) {
Figure f = new Figure(10, 10); Inside
InsideArea
Areafor
forRectangle.
Rectangle.
Rectangle r = new Rectangle(9, 5);
Area
Areaisis45
45
Triangle t = new Triangle(10, 8);
Inside
InsideArea
Areafor
forTriangle.
Triangle.
Figure figref; Area
Areaisis40
40
Area
Areafor
forFigure
Figureisisundefined
undefined
figref = r;
Area
Areaisis00
System.out.println("Area is " + figref.area());

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

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; 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.");
class Rectangle extends Figure { return dim1 * dim2 / 2;
Rectangle(double a, double b) {
}
super(a, b);
} }
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);

Figure figref; // this is OK, no object is created

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!");
}
}

Compile time error will


be the result.
Use final to prevent Inheritance
 Sometimes you will want to prevent a class
from being inherited.
 The class should declared as final.
 Implicitly declare all of its methods as final.
 It s illegal to declare a class both final and abstract.
Problems
 Create a superclass named “vehicle” which has
three instance variable, ‘speed’, ‘color’, ‘weight’.
Use Parameterized constructor to initialized
instance variables. Now provide two subclasses
named “Car” and “Boat” that inherits “vehicle”
class. ‘Car’ has additional attributes like
‘number_of_wheel’, ‘number_of_door’ etc. And
‘Boat’ has also some specific attribute like
‘number_of_sail’, ‘number_of_scull’ etc. Use
keyword ‘super’ in the subclass constructor. Write
a class “TestInheritance” to demonstrate the
capabilities of inheritance.
Problem
 Create a superclass named “MemberOfUniversity”
has some common attributes such as ‘name’,
‘address’ and has a abstract method show() to print
the value of instance variables. Use Parameterized
constructor to initialized instance variables. Provide
two subclass ‘Student’ and ‘Teacher’ that inherits
‘MemberOfUniversity’. Now ‘student’ has some
specific attributes likes ‘Roll’, ‘Year’, ‘semester’
and ‘Teacher’ has some attributes like
‘designation’, ‘salary’. Use keyword ‘super’ in the
subclass constructor. Also use “dynamic method
dispatch” for the overriding method. Write a class
“TestInheritance” to demonstrate the capabilities
of inheritance.

You might also like