Unit 3
Unit 3
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
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:
1
3.1. INTRODUCTION TO INHERITANCE
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
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.
class SuperClass
{
// features shared by all descendants...
}
class SubClassextends SuperClass
{
// features shared by descendants of SubClass...
}
2. Multi-Level Inheritance
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.
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:
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.
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.
Disadvantages of Inheritance
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:
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++;
}}
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. ");
}
}
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.
1) Method Overloading
2) Method Overriding
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.
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
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.
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:
16
{
System.out.println ("I'm the method of DerivedClass");
}
}
Output:
2. object type (NOT reference variable type) determines which overridden method will be used
at runtime
17
Runtime and Compile time polymorphism
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.
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 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.
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.
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).
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?
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