[go: up one dir, main page]

0% found this document useful (0 votes)
14 views41 pages

3.1 Inheritance

Oop inheritance

Uploaded by

hasibshahriar04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views41 pages

3.1 Inheritance

Oop inheritance

Uploaded by

hasibshahriar04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

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

// 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:
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

⚫ 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 // compute and return volume
Box(double w, double h, double d) { double volume() {
width = w; return width * height * depth;
height = h; }
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();
}
}
// 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).

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;
} i of class B 3
void show()
i of class A 1
{
System.out.println("i of class B "+i); j of class A 2
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; }
}
// 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 super(len);
are specified weight = m;
BoxWeight(double w, double h,
}
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: 3


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 and j: 1 2
super.show(); // this calls A's show()
K: 3
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)
See .docx note for this topic and DMD
A superclass variable can
Reference a subclass object
aka Upcasting
 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 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
}
}

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 Area for Rectangle.
Rectangle r = new Rectangle(9, 5);
Area is 45
Triangle t = new Triangle(10, 8);
Inside Area for Triangle.
Figure figref; Area is 40
Area for Figure is undefined
figref = r; Area is 0
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. 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);
} }

// 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.
As without inheritance overriding won't be possible
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