0% found this document useful (0 votes)
5 views54 pages

Inheritance

The document discusses the concept of inheritance in object-oriented programming, explaining how subclasses inherit properties and methods from superclasses to promote code reuse and reduce duplication. It provides examples in Java, illustrating the relationships between classes, the use of the 'extends' keyword, and the significance of the 'super' keyword. Additionally, it covers types of inheritance, including single and multilevel inheritance, while noting that Java does not support multiple inheritance.

Uploaded by

jeremiahndegwa9
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)
5 views54 pages

Inheritance

The document discusses the concept of inheritance in object-oriented programming, explaining how subclasses inherit properties and methods from superclasses to promote code reuse and reduce duplication. It provides examples in Java, illustrating the relationships between classes, the use of the 'extends' keyword, and the significance of the 'super' keyword. Additionally, it covers types of inheritance, including single and multilevel inheritance, while noting that Java does not support multiple inheritance.

Uploaded by

jeremiahndegwa9
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

9/23/2015 By: Ambrose Njeru [BSc, MSc.

Computer Science] 1
Introduction
Inheritance, is a form of software reuse where
one class acquires the properties (methods and
fields) of another class.
The class which inherits the properties of other is
known as subclass (derived class, child class)
and the class whose properties are inherited is
known as superclass (base class, parent class).
With object-oriented programming,
programmers focus on the commonalities
among objects in the system rather than on
the special cases.

9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 2


Introduction
Different objects have similar things in common.
For example the following Animals all have legs: a
Cow, a Duck and a Dog. However, this objects still
have some differences. a Cow and a Dog have 4 legs
while a Duck has 2.
Vehicles have wheels, they move, they can
halt/stop, etc.
There are many specific types of Vehicles - Cars,
bicycle, trucks, busses etc. They all share
(inherit) attributes of a vehicle. But each is more
specific:
 Cars have 4 wheels, carry5 people
 Bicycles have 2 wheels, carry 1 person
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 3
Why Inheritance?
When creating classes from which the
objects are created, we may have to
duplicate the common properties and
behaviors.
This would lead to a lot of code duplication.
e.g. since a cow, a duck and a dog all have
legs, we don’t have to redefine the
assignment of legs each time we create each
of the objects(duplication).
The solution is to reuse that functionality
from where italready exists.
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 4
Why Inheritance?
Inheritance allows you to write new classes
that inherit from existing classes.
 For example Vehicle becomes the superclass
of Car, Truck, Bus and Bicycle.
 In this case Car, Truck, Bus and Bicycle are
subclasses.
In Java, each class is allowed to have one direct
superclass (parent), and each superclass has the
potential for an unlimited number of
subclasses(child).

9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 5


Super classes & Subclasses
An object of one class "is an" object of another
class as well. For example, in geometry, a rectangle
is a quadrilateral (as are squares, parallelograms
and trapezoids).
In Java, class Rectangle can be said to inherit from
class Quadrilateral. In this context, class
Quadrilateral is a superclass and class Rectangle is
a subclass.
A class becomes either a superclass, supplying
members to other classes, or a subclass, inheriting
its members from other classes.

9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 6


Inheritance Basics
Java supports inheritance by allowing one class to
incorporate another class into its declaration.
This is done by using the extends keyword.
 Example:
class Calculation {
int z;
p u b l i c vo i d a d d i t i o n ( i n t x , i n t y ) {
z = x + y;
[Link]("The sum of the
g i ve n n u m b e r s : " + z ) ;
}
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 7
Inheritance Basics
publi c voi d S ubt ra ction( int x , i nt y ) {
z = x - y;
[Link] ("The di fference
b e t we e n t h e g i v e n n u m b e r s : " + z ) ;
}}
public class MyCalculation extends
Calculation {
publi c voi d mult i plica tion(int x , i nt y ) {
z = x * y;
[Link]("The product of the
give n numbe rs:" +z);
}
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 8
Inheritance Basics
p u b l i c s t a t i c vo i d m a i n ( S t r i n g a r g s [ ] ) {
int a = 20,
b = 10;
MyCalculation demo = new
MyCalculation();
d e m o. a d d i t i o n ( a , b ) ;
d e m o. S u b t r a c t i o n ( a , b ) ;
d e m o. m u l t i p l i c a t i o n ( a , b ) ;
}
}
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 9
Inheritance Basics
When an object to MyCalculation class is
created, a copy of the contents of the superclass
is made within it. That is why, using the object of
the subclass you can access the members of a
superclass.
A subclass inherits all the members (fields,
methods, and nested classes) from its superclass.
Constructors are not members, so they are not
inherited by subclasses, but the constructor of
the superclass can be invoked from the subclass.

9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 10


Inheritance Example
/ / Asimple class hierarchy.
/ / Aclass for two-dimensional objects.
class TwoDShape {
double width;
double height;
void showDim()
{
[Link]("Width and height are "+
width + "and "+height);
}
}
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 11
Inheritance Example
// A subclass of TwoDShape for triangles.
class Triangle extends TwoDShape {
String style;
double area(){
return width * height / 2;
}
void showStyle() {
[Link]("Triangle is "+ style);
}
}
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 12
Inheritance Example
class Shapes {
public static void main(String args[]) {
Triangle t1 = new Triangle();
Triangle t2 = newTriangle();
[Link] = 4.0;
[Link] = 4.0;
[Link] = "Isosceles";
[Link] = 8.0;
[Link] = 12.0;
[Link] = "Right";

9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 13


Inheritance Example
[Link]("Info for t1: ");
[Link]();
[Link]();
[Link]("Area is "+[Link]());
[Link]();
[Link]("Info for t2: ");
[Link]();
[Link]();
[Link]("Area is "+[Link]());
}
}
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 14
Inheritance Basics
TwoDShape defines the attributes of a “generic”
two-dimensional shape, such as a square,
rectangle, triangle, and so on.
The Triangle class creates a specific type of
TwoDShape, in this case, a triangle.
The Triangle class includes all of TwoDObject
and adds the field style, the method area( ), and
the method showStyle( ).
A description of the type of triangle is stored in
style, area( ) computes and returns the area of the
triangle, and showStyle( ) displays the triangle
style.
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 15
Inheritance Basics
Because Triangle includes all of the members
of its superclass, TwoDShape, can access width
and height inside area( ).
Also, inside main( ), objects t1 and t2 can refer to
width and height directly, as if they were part of
Triangle.
Even though TwoDShape is a superclass for
Triangle, it is also a completely independent,
stand-alone class.
Being a superclass for a subclass does not mean
that the superclass cannot be used by itself.

9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 16


Inheritance Basics
You can specify only one superclass for any subclass
that you create. Java does not support the
inheritance of multiple superclasses into a single
subclass.
You can, however, create a hierarchy of inheritance
in which a subclass becomes a superclass of
another subclass.
No class can be a superclass of itself.
A major advantage of inheritance is that once you
have created a superclass that defines the
attributes common to a set of objects, it can be
used to create any number of more specific
subclasses.
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 17
The super Keyword
The super keyword is similar to this keyword.
The super keyword is used to:
Differentiate the members of superclass
from the members of subclass, if they have
same names. If the members of the
superclass have the same names as the sub
class, we differentiate these variables as
follows:
[Link]
[Link]();
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 18
The super Keyword
class Superclass {
int num = 20;
// display method of superclass
public void display() {
[Link]("This is the display method
of superclass");
}}
public class Subclass extends Superclass {
int num = 10;
// display method of sub class
public void display() {
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 19
The super Keyword
[Link]("This is the display method
of subclass");
}
public void mymethod() {
// Instantiating subclass
Subclass sub = new Subclass();
//Invoking the display() method of subclass
[Link]();
//Invoking the display() method of superclass
[Link]();
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 20
The super Keyword
//printing the value of variable num of subclass
[Link](“Value of the variable
named num in sub class:"+ [Link]);
//printing the value of variable num of superclass
[Link](“Value of the variable
named num in super class:"+ [Link]);
}
public static void main(String args[]) {
Subclass obj = new Subclass();
[Link]();
}}
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 21
The super Keyword
Invoke the superclass constructor from
subclass. If a class is inheriting the
properties of another class, the subclass
automatically acquires the default
constructor of the superclass. But if you
want to call a parameterized constructor of
the superclass, you need to use the super
keyword as shown below.
super(values);

9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 22


The super Keyword
class Superclass {
int age;
Superclass(int age) {
[Link] = age;
}
public void getAge() {
[Link]("The value of the variable
named age in super class is: " +age);
}
}
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 23
The super Keyword
public class Subclass extends Superclass {
Subclass(int age) {
super(age);
}
public static void main(String argd[]) {
Subclass s = new Subclass(24);
[Link]();
}
}

9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 24


IS-A Relationship
IS-A is a way of saying: This object is a type
of that object.
Example:
public class Animal {
}
public class Mammal extends Animal {
}
public class Reptile extends Animal {
}
public class Dog extends Mammal {
}

9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 25


IS-A Relationship
Now, based on the above example, in OOP
terms, the following are true −
Animal is the superclass of Mammal
class.
Animal is the superclass of Reptile class.
Mammal and Reptile are subclasses of
Animal class.
Dog is the subclass of both Mammal and
Animal classes.

9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 26


IS-A Relationship
If we consider the IS-A relationship, we can
say −
Mammal IS-A Animal
Reptile IS-A Animal
Dog IS-A Mammal
Hence: Dog IS-A Animal as well
With the use of the extends keyword, the
subclasses will be able to inherit all the
properties of the superclass except for the
private properties of the superclass.
We can assure that Mammal is actually an
Animal with the use of the instance
operator.
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 27
IS-A Relationship
class Animal { }
class Mammal extends Animal { }
class Reptile extends Animal { }
public class Dog extends Mammal {
public static void main(String args[]) {
Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();
[Link](m instanceof Animal);
[Link](d instanceof Mammal);
[Link](d instanceof Animal);
}
}9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 28
HAS-A Relationship
This relationship helps to reduce duplication
of code as well as bugs.
public class Vehicle{ }
public class Speed{ }
public class Van extends Vehicle {
private Speed sp;
}
This shows that class Van HAS-A Speed.
By having a separate class for Speed, we do
not have to put the entire code that belongs
to speed inside the Van class, which makes it
possible to reuse the Speed class in multiple
applications.
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 29
Types of Inheritance

9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 30


Types of Inheritance

NB: Java does not support multiple


inheritance, meaning that a class cannot
extend more than one class. Therefore
following is illegal −
public class extends Animal, Mammal{}
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 31
Single Inheritance Example
class Animal {
void eat(){
[Link]("eating...");}
}
class Dog extends Animal {
void bark(){
[Link]("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}}
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 32
Multilevel Inheritance Example
class Animal
{
void eat()
{
[Link]("eating...");}
}
class Dog extends Animal
{
void bark(){
[Link]("barking...");}
}
class BabyDog extends Dog{
void weep()
{
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 33
Multilevel Inheritance Example
[Link]("weeping...");
}
}
class TestInheritance{
public static void main(String args[])
{
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}
}

9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 34


Hierarchical Inheritance Example
class Animal
{
void eat()
{
[Link]("eating...");}
}
class Dog extends Animal
{
void bark()
{
[Link]("barking...");}
}
class Cat extends Animal
{
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 35
Hierarchical Inheritance Example
void meow()
{
[Link]("meowing...");}
}
class TestInheritance
{
public static void main(String args[])
{
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}
}
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 36
Member Access & Inheritance
Instance variable of a class is always declared
private to prevent its unauthorized use or
tampering.
Inheriting a class does not overrule the private
access restriction. Thus, even though a subclass
includes all of the members of its superclass, it
cannot access those members of the superclass
that have been declared private.
To be able to access the private members, we use
accessor methods.

9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 37


Member Access & Inheritance
class TwoDShape {
private double width;
private double height;
/ / Accessor methods for width and height.
double getWidth() {
return width;
}
double getHeight() {
return height;
}

9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 38


Member Access & Inheritance
void setWidth(double w) {
width = w;
}
void setHeight(double h) {
height = h;
}
void showDim() {
[Link]("Width and height are "+
width + "and "+height);
}
}
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 39
Member Access & Inheritance
class Triangle extends TwoDShape { String
style;
double area() {
return getWidth() * getHeight() / 2;
}
void showStyle() {
[Link]("Triangle is "+style);
}}
class Shapes2 {
public static void main(String args[])
{
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 16
Member Access & Inheritance
Triangle t1 = new Triangle();
Triangle t2 = new Triangle();
[Link](4.0);
[Link](4.0);
[Link] = "Isosceles";
[Link](8.0);
[Link](12.0);
[Link] = "Right";
[Link]("Info for t1: ");
[Link]();
[Link]();
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 41
Member Access & Inheritance
[Link]("Area is "+ [Link]());
[Link]();
[Link]("Info fort2: ");
[Link]();
[Link]();
[Link]("Area is "+ [Link]());
}
}

9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 42


Overriding Methods
When you create a subclass by extending an
existing class, the new subclass contains data
and methods that were defined in the original
superclass.
In this case, any child class object has all the
attributes of its parent.
Sometimes, however, the superclass data fields
and methods are not entirely appropriate for
the subclass objects; in these cases, you want
to override the parent class members.
If a class inherits a method from its superclass,
then there is a chance to override the method
provided that it is not marked final.
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 43
Overriding Methods
The benefit of overriding is: ability to define a
behavior that's specific to the subclass type,
which means a subclass can implement a
parent class method based on its requirement.
In object-oriented terms, overriding means to
override the functionality of an existing
method.
When you create a method in a child class that has
the same name and parameter list as a method in its
parent class, you override the method in the parent
class.

9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 44


Overriding Methods
Each subclass method overrides any method in the
parent class that has both the same name and
parameter list.
If the parent class method has the same name but
a different parameter list, the subclass method
does not override the parent class version; instead,
the subclass method overloads the parent class
method, and any subclass object has access to both
versions.
When an overridden method is called from within
a subclass, it will always refer to the version of that
method defined by the subclass and the version of
the method defined by the superclass will be
hidden.
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 45
Overriding Methods
class Animal
{
public void move()
{
[Link]("Animals can move");
}
}
class Dog extends Animal
{
public void move() {
[Link]("Dogs can walk and run");
}
}
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 46
Overriding Methods
public class TestDog {
public static void main(String args[]) {
// Animal reference and object
Animal a = new Animal();
// Animal reference but Dog object
Animal b = new Dog();
// runs the method in Animal class
[Link]();
// runs the method in Dog class
[Link]();
}
}
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 47
Overriding Methods
In the above example, you can see that even
though b is a type of Animal it runs the move
method in the Dog class. The reason for this is: In
compile time, the check is made on the reference
type. However, in the runtime, JVM figures out the
object type and would run the method that
belongs to that particular object.
Therefore, in the above example, the program will
compile properly since Animal class has the
method move. Then, at the runtime, it runs the
method specific for that object.

9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 48


Overriding Methods
class Animal {
public void move() {
[Link]("Animals can move");
}
}
class Dog extends Animal {
public void move() {
[Link]("Dogs can walk and run");
}
public void bark() {
[Link]("Dogs can bark");
}
}
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 49
Overriding Methods
public class TestDog {
public static void main(String args[]) {
// Animal reference and object
Animal a = new Animal();
// Animal reference but Dog object
Animal b = new Dog();
// runs the method in Animal class
[Link]();
// runs the method in Dog class
[Link]();
[Link]();
}
}
9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 50
Overriding Methods
Output
[Link]: error: cannot find symbol
[Link]();
^
symbol: method bark()
location: variable b of type Animal
1 error

This program will throw a compile time error


since b's reference type Animal doesn't have a
method by the name of bark.

9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 51


Rules for Overriding Methods
The argument list should be exactly the same as
that of the overridden method.
The return type should be the same or a subtype
of the return type declared in the original
overridden method in the superclass.
The access level cannot be more restrictive than
the overridden method's access level. For
example: If the superclass method is declared
public then the overridding method in the sub
class cannot be either private or protected.
Instance methods can be overridden only if they
are inherited by the subclass.

9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 52


Rules for Overriding Methods
A method declared final cannot be overridden.
A method declared static cannot be overridden
but can be re-declared.
If a method cannot be inherited, then it cannot
be overridden.
A subclass within the same package as the
instance's superclass can override any superclass
method that is not declared private or final.
A subclass in a different package can only
override the non-final methods declared public
or protected.

9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 53


Rules for Overriding Methods
An overriding method can throw any uncheck
exceptions, regardless of whether the overridden
method throws exceptions or not. However, the
overriding method should not throw checked
exceptions that are new or broader than the ones
declared by the overridden method. The
overriding method can throw narrower or fewer
exceptions than the overridden method.
Constructors cannot be overridden.

9/23/2015 By: Ambrose Njeru [BSc, MSc. Computer Science] 54

You might also like