0% found this document useful (0 votes)
21 views22 pages

Unit 3

Unit 3 covers inheritance and polymorphism in object-oriented programming, explaining their significance, types, and examples. It details inheritance mechanisms like single, multi-level, hierarchical, and multiple inheritance, along with method overriding and the use of the final keyword. The unit also discusses the advantages and disadvantages of inheritance, emphasizing code reusability and potential tight coupling between classes.

Uploaded by

amanuel
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)
21 views22 pages

Unit 3

Unit 3 covers inheritance and polymorphism in object-oriented programming, explaining their significance, types, and examples. It details inheritance mechanisms like single, multi-level, hierarchical, and multiple inheritance, along with method overriding and the use of the final keyword. The unit also discusses the advantages and disadvantages of inheritance, emphasizing code reusability and potential tight coupling between classes.

Uploaded by

amanuel
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/ 22

UNIT 3:

3: INHERITANCE AND POLYMORPHISM

Contents
3.0. Aims and Objectives
3.1. Introduction to Inheritance
3.2. Inheritance Basics
Basics
3.3. Method Overriding
3.4. Advantages and disadvantages of inheritance
3.5. Examples of Inheritance
Inheritance
3.6. Introduction to Polymorphism
3.7. Summary
3.8. Model Examination Questions

3.0. AIMS AND OBJECTIVES

In this unit we will discuss the the importance of inheritance and polymorphism in object
oriented programming. We will discover the basics of inheritance such as super and
subclasses, types of inheritance with sample examples and also the role of inheritance in
OOP. At the end of the chapter we will try to discuss the nature of polymorphism in detail.
After you have studied this unit, you will be able to:

• know the role of inheritance and polymorphism in object oriented programming


• Understand how to inheritance used in a program
• Differentiate the method overriding and method overloading with java
programming examples

1
3.1. INTRODUCTION TO INHERITANCE
INHERITANCE

Inheritance is one of the cornerstones of object-oriented programming because it allows


the creation of hierarchical classifications. Using inheritance, you can create a general class
that defines traits common to a set of related items. This class can then be inherited by
other, more specific classes, each adding those things that are unique to it. In the
terminology of Java, a class that is inherited is called a superclass. The class that does the
inheriting is called a subclass. Therefore, a subclass is a specialized version of a superclass.
It inherits all of the members defined by the superclass and adds its own, unique elements.
Reusability that is building new components by utilizing existing components- is important
aspect of OO paradigm. It is always good/ “productive” if we are able to reuse something
that is already exists rather than creating the same all over again. This is achieved by
creating new classes, reusing the properties of existing classes. This mechanism of deriving
a new class from existing/old class is called “inheritance”.

The term inheritance refers to the fact that one class can inherit part or all of its structure
and behavior from another class. The class that does the inheriting is said to be a subclass
of the class from which it inherits. If class B is a subclass of class A, we also say that class A
is a superclass of class B. A subclass can add to the structure and behavior that it inherits. It
can also replace or modify inherited behavior (though not inherited structure).

§ Inheritance is the mechanism of deriving new class from old one, old class is known
as superclass and new class is known as subclass. The subclass inherits all of its
instances variables and methods defined by the superclass and it also adds its own
unique elements.
§ Inheritance is a mechanism for enhancing existing classes. If you need to implement
a new class and a class representing a more general concept is already available,
then the new class can inherit from the existing class.

2
3.2. INHERITANCE BASICS

Super classes and sub classes

Ø A superclass class is defined as follows:


The more general class that forms the basis for inheritance (extended class) is called the
superclass.
class Superclass
{
// attributes and behaviors shared by all subclasses...
}

Ø A subclass/child class is defined as follows:


class Subclass1 extends Superclass
{
// attributes and behaviors unique to Subclass1...
}

Inheritance is implemented in Java using the extends clause. The extends Superclass
clause specifies the inheritance. It indicates that any object of type Subclass1 is also an
object of type Superclass and thus that a Subclass1 object can do anything that a Superclass
object can do. This construct provides considerable power for code sharing and reuse. The

3
keyword “extends” signifies that the properties of superclass are extended to the subclass.
That means subclass contains its own members as well of those of the super class. This
kind of situation occurs when we want to enhance properties of existing class without
actually modifying it.

Types of Inheritance in Java


1. Single Inheritance –one class extends one class only

class SuperClass
{
// features shared by all descendants...
}
class SubClassextends SuperClass
{
// features shared by descendants of SubClass...
}

2. Multi-Level Inheritance

Multilevel inheritance refers to a mechanism in OO technology where one can inherit


from a derived class, thereby making this derived class the base class for the new class.
Multilevel inheritance is a recursive mechanism and can therefore be used to implement
multiple levels of sharing. As you can see below, flow diagram C is subclass or child class of
B and B is a child class of A.

It’s pretty clear with the diagram that in Multilevel inheritance there is a concept of
grandparent class. If we take the example of the diagram then class C inherits class B and
class B inherits class A which means B is a parent class of C and A is a parent class of B. So

4
in this case class C is implicitly inheriting the properties and method of class A along with B
that’s what is called multilevel inheritance.

The Java extends clause can be used as shown in the code here on the left to produce the
class structure shown on the right.
class SuperClassA {
// features shared by all descendants...
}
class SubClassB extends SuperClassA {
// features shared by descendants of SubClass...
}
class SubClassC extends SubClassA {
// features unique to SubSubClass...
}

In this structure, objects of type SubSubClass inherit features from both SubClass and
SuperClass. This mechanism provides the ability to create tree-shaped class hierarchies
that can be used to share features amongst subsets of subclasses.
3. Hierarchal Inheritance -one class is extended by many subclasses. It is one-to-many
relationship. In Java it is common to group classes in complex inheritance hierarchies.

5
The classes representing the most general concepts are near the root, more specialized
classes towards the branches.

class SuperClassA {
// features shared by all descendants...
}
class SubClassBextends SuperClassA{
// features shared by descendants of SubClass...
}
class SubClassCextends SuperClassA
{
// features unique to SubSubClass...
}

4. Multiple Inheritance
When a derived class is created from more than one base class then that inheritance is
called as multiple inheritance. But multiple inheritance is not supported by java using
classes and can be done using interfaces.

Inheriting Methods
When you form a subclass of a given class, you can specify additional instance fields and
methods. When defining the methods for a subclass, there are three possibilities:

6
I. You can override methods from the superclass: If you specify a method with the same
signature (same name and parameter types), it overrides the method of the same name
in the superclass. Whenever the method is applied to an object of the subclass type, the
overriding method, and not the original method, is executed.
II. You can inherit methods from the superclass: If you do not explicitly override a
superclass method, you automatically inherit it. The superclass method can be applied
to the subclass objects
III. You can define new methods: If you define a method that did not exist in the
superclass, then the new method can be applied only to subclass objects.

Inheriting Instance Fields


The situation for instance fields is quite different. You can never override instance fields.
For fields in a subclass, there are only two cases:
I. The subclass inherits all fields from the superclass: All instance fields from the
superclass are automatically inherited
II. Any new instance fields that you define in the subclass are present only in subclass
objects
§ What happens if you define a new field with the same name as a superclass field? This is
legal but extremely undesirable.
§ Although a subclass includes all of the members of its superclass, it cannot access those
members of the superclass that have been declared as private.

Check your progress-1


1. What is inheritance in OOP?
_________________________________________________________________________________________________
_________________________________________________________________________________________________
2. List and explain at least three types of inheritance with example?
_________________________________________________________________________________________________
_________________________________________________________________________________________________

7
3.3. METHOD OVERRIDING

In a class hierarchy, when a method in a subclass has the same name and type signature
as a method in its superclass, then the method in the subclass is said to override the
method in the superclass. When an overridden method is called from within its subclass,
it will always refer to the version of that method defined by the subclass. The version of
the method defined by the superclass will be hidden. Consider the following:

Using of final with Inheritance


The keyword final has three uses. First, it can be used to create the equivalent of a named
constant. The other two uses of final apply to inheritance.
1. Final Variable: once a variable is declared as final, its value cannot be changed during
the scope of the program.
2. Final Method: Method declared as final cannot be overridden
3. Final Class: a final class cannot be overridden
Both are examined here.
Using final to Prevent Overriding
While method overriding is one of Java’s most powerful features, there will be times when
you will want to prevent it from occurring. To disallow a method from being overridden,
specify final as a modifier at the start of its declaration. Methods declared
As final cannot be overridden. The following fragment illustrates final:
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!");
}
}
Ø Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to
do so, a compile-time error will result.

8
Methods declared as final can sometimes provide a performance enhancement: The
compiler is free to inline calls to them because it “knows” they will not be overridden by
a subclass. When a small final method is called, often the Java compiler can copy the byte
code for the subroutine directly inline with the compiled code of the calling method,
thus eliminating the costly overhead associated with a method call. Inlining is an option
only with final methods. Normally, Java resolves calls to methods dynamically, at run
time. This is called late binding. However, since final methods cannot be overridden, a
call to one can be resolved at compile time. This is called early binding.

Using final to Prevent Inheritance


Sometimes you will want to prevent a class from being inherited. To do this, precede the
class declaration with final. Declaring a class as final implicitly declares all of its methods
as final, too. As you might expect, it is illegal to declare a class as both abstract and final
since an abstract class is incomplete by itself and relies upon its subclasses to provide
complete implementations. Here is an example of a final class:
final class A {
//…
}
// The following class is illegal.
class B extends A {// ERROR! Can't subclass A
//…
}
As the comments imply, it is illegal for B to inherit A Since A is declared as final.

Check your progress-2


1. What is method overriding? Explain it with example?
_________________________________________________________________________________________________
_________________________________________________________________________________________________
__________________________________________________

9
3.4. ADVANTAGES AND DISADVANTAGES
DISADVANTAGES OF INHERITANCE
INHERITANCE

One of the key benefits of inheritance is to minimize the amount of duplicate code in an
application by sharing common code amongst several subclasses. Where equivalent code
exists in two related classes, the hierarchy can usually be refactored to move the common
code up to a mutual superclass. This also tends to result in a better organization of code
and smaller, simpler compilation units. Inheritance can also make application code more
flexible to change because classes that inherit from a common superclass can be used
interchangeably.

Let’s see some of the advantages:


Reusabilityàfacility to use public methods of base class without rewriting the same
Extensibilityàextending the base class logic as per business logic of the derived class
Data hidingàbase class can decide to keep some data private so that it cannot be altered
by the derive class
OverridingàWith inheritance, we will be able to override the methods of the base class so
that meaningful implementation of the base class method can be designed in the derived
class.

Disadvantages of Inheritance

1. Both classes (super and subclasses) are tightly-coupled.


2. As they are tightly coupled (binded each other strongly with extends keyword), they
cannot work independently of each other.
3. Changing the code in super class method also affects the subclass functionality.
4. If super class method is deleted, the code may not work as subclass may call the
super class method with super keyword. Now subclass method behaves
independently.

Check your progress-3


1. List at least three advantages and disadvantages of using inheritance in OOP?
_________________________________________________________________________________________________
________________________________________________________________________________________________

10
3.5. EXAMPLES OF INHERITANCE
INHERITANCE

1. Single inheritance: it is the simplest form of inheritance involving one super class and
one subclass. Following program is a simple example of simple inheritance:

/* define the super class 'X' */


class X
{
protected int a; // variable 'a' is visible to subclass
X()
{
}
X(intval)
{
a = val;
}
public void increment()
{
a++;
}
}

/* define the subclass 'Y' which inherits from 'X'


* variable 'a' and method 'increment' is reflected in 'Y'
*/
class Y extends X {
int b, c;
Y() { }
Y(int val1, int val2, int val3) {
super(val1); // call the constructor of super class
b = val2; c = val3;
}
void display() {
System.out.println("a = " + a + " b = " + b + " c = " + c);
}
}

public class SingleInheritanceDemo {


public static void main(String args[]) {
Y obj = new Y(3, 8, 5);
obj.increment();
obj.display();
}}

2. Multi-level Inheritance :Consider a base class A and another class B which inherits
from A. Now another class C inherits from B. So, B becomes the subclass for C and super

11
class for A. This kind of inheritance is known as multilevel inheritance. See the program
below:
class X {
protected int a;
X() { }
X(intval) {
a = val;
}
public void incrementX() {
a++;
}}

/* Variables and methods of 'X' are reflected in Y */


class Y extends X {
protected int b;
Y() { }
Y(int val1, int val2) {
super(val1);
b = val2;
}
public void incrementY() {
b++;
}}
/* Variables and methods of 'X' and 'Y' are reflected in Z */
class Z extends Y {
protected int c;
Z() { }
Z(int val1, int val2, int val3) {
super(val1, val2);
c = val3;
}
public void incrementZ() {
incrementX();
incrementY();
c++;
}
void display() {
System.out.println("a = " + a + " b = " + b + " c = " + c);
}}
public class MultilevelInheritanceDemo {
public static void main(String args[]) {
Z obj = new Z(3, 8, 5);
obj.incrementZ();
obj.display();
}
}

12
3. Hierarchical Inheritance: In this form of inheritance multiple classes inherits from a
single class i.e. there is one super class and multiple subclasses. This form of inheritance
is commonly used in Java program design. Following program illustrates the concept:

class Fruit {
protected void fruitInfo() {
System.out.println("I am a fruit. ");
}
}

// class 'Mango' inherits from class 'Fruit'


class Mango extends Fruit {
public void mangoInfo() {
fruitInfo(); // calling base class function
System.out.println("My name is mango. ");
}
}

// class 'Apple' inherits from class 'Fruit'


class Apple extends Fruit {
public void appleInfo() {
fruitInfo();// calling base class function
System.out.println("My name is apple. ");
}
}

public class HierarchicalInheritanceDemo {


public static void main(String args[]) {
Mango m = new Mango();
Apple a = new Apple();
m.mangoInfo();
a.appleInfo();
}}

13
3.6. INTRODUCTION TO POLYMORPHISM
POLYMORPHISM

The term polymorphism means “a method the same as another in spelling but with
different behavior.” The computer differentiates between (or among) methods depending
on either the method signature (after compile) or the object reference (at run time). Simply
put, polymorphism is what allows actions to act differently based on the object performing
the action or the object the action is being performed on. Let's just use a super simple, real
life example. What is a typical sound that a cat makes? Let's just say it's meow. Let's call
this action makeSound () because remember, a method can represent an action. What
sound does a dog make? Let's just say a dog goes woof. We can also call this action
makeSound (). Let's also just pretend that all animals can makeSound (). Thus, makeSound
(), depending on the type of animal, does something different. The action acts differently
based on the object.

Polymorphism is the capability of a method to do different things based on the object that it
is acting upon. In other words, polymorphism allows you define one interface and have
multiple implementations.

• It is a feature that allows one interface to be used for a general class of actions.
• An operation may exhibit different behavior in different instances.
• The behavior depends on the types of data used in the operation.
• It plays an important role in allowing objects having different internal structures to
share the same external interface.
• Polymorphism is extensively used in implementing inheritance.

Types of polymorphism in java

1) Method Overloading

2) Method Overriding

Let’s try to see them step by step.

1) Method Overloading:

In Java, it is possible to define two or more methods of same name in a class, provided that

14
their argument list or parameters are different. This concept is known as Method
Overloading.

1. To call an overloaded method in Java, it is must to use the type and/or number of
arguments to determine which version of the overloaded method to actually call.

2. Overloaded methods may have different return types; the return type alone is
insufficient to distinguish two versions of a method. .

3. When Java encounters a call to an overloaded method, it simply executes the version
of the method whose parameters match the arguments used in the call.

4. It allows the user to achieve compile time polymorphism.

5. An overloaded method can throw different exceptions.

6. It can have different access modifiers.

Example:
class Overload
{
void demo (int a)
{
System.out.println ("a: " + a);
}
void demo (int a, int b)
{
System.out.println ("a and b: " + a + "," + b);
}
double demo (double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class MethodOverloading
{
public static void main (String args [])
{
Overload Obj = new Overload ();
double result;
Obj.demo(10);
Obj.demo(10, 20);
result = Obj.demo(5.5);
System.out.println("O/P : " + result);
}
}

15
Here the method demo() is overloaded 3 times: first having 1 int parameter, second one
has 2 int parameters and third one is having double arg. The methods are invoked or called
with the same type and number of parameters used.

Output:

a: 10
a and b: 10,20
double a: 5.5
O/P : 30.25

Rules for Method Overloading


1. Overloading can take place in the same class or in its sub-class.

2. Constructor in Java can be overloaded

3. Overloaded methods must have a different argument list.

4. Overloaded method should always be the part of the same class (can also take place in
sub class), with same name but different parameters.

5. The parameters may differ in their type or number, or in both.

6. They may have the same or different return types.

7. It is also known as compile time polymorphism.

2) Method Overriding

Child class has the same method as of base class. In such cases child class overrides the
parent class method without even touching the source code of the base class. This feature is
known as method overriding. Example:

public class BaseClass


{
public void methodToOverride() //Base class method
{
System.out.println ("I'm the method of BaseClass");
}
}
public class DerivedClass extends BaseClass
{
public void methodToOverride() //Derived Class method

16
{
System.out.println ("I'm the method of DerivedClass");
}
}

public class TestMethod


{
public static void main (String args []) {
// BaseClass reference and object
BaseClass obj1 = new BaseClass();
// BaseClass reference but DerivedClass object
BaseClass obj2 = new DerivedClass();
// Calls the method from BaseClass class
obj1.methodToOverride();
//Calls the method from DerivedClass class
obj2.methodToOverride();
}
}

Output:

I'm the method of BaseClass


I'm the method of DerivedClass

Rules for Method Overriding:

1. applies only to inherited methods

2. object type (NOT reference variable type) determines which overridden method will be used
at runtime

3. Overriding method can have different return type

4. Overriding method must not have more restrictive access modifier

5. Abstract methods must be overridden

6. Static and final methods cannot be overridden

7. Constructors cannot be overridden

8. It is also known as Runtime polymorphism.

17
Runtime and Compile time polymorphism

There are two types of polymorphism in java- Runtime polymorphism (Dynamic


polymorphism) and Compile time polymorphism (static polymorphism).

Runtime Polymorphism (or Dynamic polymorphism)

Method overriding is a perfect example of runtime polymorphism. In this kind of


polymorphism, reference of class X can hold object of class X or an object of any sub classes
of class X. For e.g. if class Y extends class X then both of the following statements are valid:

Y obj = new Y();


//Parent class reference can be assigned to child object
X obj = new Y();

Since in method overriding both the classes(base class and child class) have same method,
compile doesn’t figure out which method to call at compile-time. In this case JVM(java
virtual machine) decides which method to call at runtime that’s why it is known as runtime
or dynamic polymorphism.

Lets see an example to understand it better.


public class X
{
public void methodA() //Base class method
{
System.out.println ("hello, I'm methodA of class X");
}
}

public class Y extends X


{
public void methodA() //Derived Class method
{
System.out.println ("hello, I'm methodA of class Y");
}
}
public class Z
{
public static void main (String args []) {
X obj1 = new X(); // Reference and object X
X obj2 = new Y(); // X reference but Y object
obj1.methodA();
obj2.methodA();
}
}
Output:

18
hello, I'm methodA of class X
hello, I'm methodA of class Y
As you can see the methodA has different-2 forms in child and parent class thus we can say
methodA here is polymorphic.

Compile time Polymorphism ( or Static polymorphism)

Compile time polymorphism is nothing but the method overloading in java. In simple terms
we can say that a class can have more than one methods with same name but with different
number of arguments or different types of arguments or both. To know more about it refer
method overloading in java.

Let’s see the below example to understand it better-


class X
{
void methodA (int num)
{
System.out.println ("methodA:" + num);
}
void methodA (int num1, int num2)
{
System.out.println ("methodA:" + num1 + "," + num2);
}
double methodA (double num) {
System.out.println("methodA:" + num);
return num;
}
}

class Y
{
public static void main (String args [])
{
X Obj = new X();
double result;
Obj.methodA(20);
Obj.methodA(20, 30);
result = Obj.methodA(5.5);
System.out.println("Answer is:" + result);
}
}
Output:
methodA:20
methodA:20,30
methodA:5.5
Answer is:5.5
As you can see in the above example that the class has three variances of methodA or we
can say methodA is polymorphic in nature since it is having three different forms. In such

19
scenario, compiler is able to figure out the method call at compile-time that’s the reason it
is known as compile time polymorphism.

Check your progress-4


1. What is the role of polymorphism in OOP? Explain in detail with example?
_________________________________________________________________________________________________
_________________________________________________________________________________________________
__________________________________________________

3.7. SUMMARY

The term inheritance refers to the fact that one class can inherit part or all of its structure
and behavior from another class. The class that does the inheriting is said to be a subclass
of the class from which it inherits. If class B is a subclass of class A, we also say that class A
is a superclass of class B. A subclass can add to the structure and behavior that it inherits.
The more general class that forms the basis for inheritance (extended class) is called the
superclass.

Inheritance is implemented in Java using the extends clause. The extends Superclass clause
specifies the inheritance. It indicates that any object of type Subclass1 is also an object of
type Superclass and thus that a Subclass1 object can do anything that a Superclass object
can do.

Single inheritance is the simplest form of inheritance involving one super class and one
subclass. Multi-level Inheritance consider a base class A and another class B which inherits
from A. Now another class C inherits from B. So, B becomes the subclass for C and super
class for A. This kind of inheritance is known as multilevel inheritance. Hierarchical
Inheritance: In this form of inheritance multiple classes inherits from a single class i.e.
there is one super class and multiple subclasses. This form of inheritance is commonly used
in Java program design.

20
Polymorphism is the capability of a method to do different things based on the object that it
is acting upon. In other words, polymorphism allows you define one interface and have
multiple implementations. There are two types of polymorphism in java- Runtime
polymorphism (Dynamic polymorphism) and Compile time polymorphism (static
polymorphism).

3.8. MODEL EXAMINATION QUESTIONS.


QUESTIONS.

I: True/False questions
1. Method overloading is a perfect example of runtime polymorphism.
2. One of the key benefits of inheritance is to minimize the amount of duplicate
code in an application by sharing common code amongst several subclasses.
3. Once a variable is declared as final, its value cannot be changed during the
scope of the program.
4. Single inheritance is the simplest form of inheritance involving one super class
and one subclass.
5. Inheritance is implemented in Java using the extend clause.
II: Short Answer Questions
1. Differentiate between method overloading and method overriding using a program?
2. When do we declare a method or class as final?
3. Write a program to find the area of Square and Rectangle by deriving them from a
class called Shape?

4. What’s the output of this program?


Class X
{
void checkA(int num)
{
System.out.println ("checkA:" + num);
}
void checkA(int num1, int num2)
{
System.out.println ("checkA:" + num1 + "," + num2);
}
double checkA(double num) {
System.out.println("checkA:" + num);
return num*num*num;
}}

21
Class Y{
public static void main (String args [])
{
X Obj = new X();
double result;
Obj.checkA(5, 10);
Obj.checkA(5);
result = Obj.checkA(2.5);
System.out.println("Answer is:" + result);
}}

5. Write your own program to illustrate how to access multiple inheritances in java?

22

You might also like