Inheritance and Polymorphism
Object Oriented Programming - CoSc2051 1
Chapter Outlines
Introduction Inheritance
Super-classes and Sub-classes
Using the super Keyword
Method Overriding and Overloading
Polymorphism
Casting Objects and Instance Operator
The Object Class
Abstract Classes
Interfaces
Using Interfaces
Object Oriented Programming - CoSc2051 2
Introduction to Inheritance
In the real world:
We inherit traits from our mother and father.
We also inherit traits from our grandmother, grandfather, and
ancestors.
We might have similar eyes, the same smile, a different height . . .
but we are in many ways "derived" from our parents.
In software:
Object inheritance is well defined!
Objects that are derived from other object "resemble" their
parents by inheriting both state (fields) and behavior (methods).
Object Oriented Programming - CoSc2051 3
Introduction to Inheritance
Object-oriented programming allows you to define new classes
from existing classes.
This is called inheritance.
The procedural paradigm focuses on designing methods and the
object-oriented paradigm couples data and methods together into
objects.
Inheritance is an important and powerful feature for reusing
software.
what is the best way to design classes so as to avoid redundancy
and make then system easy to comprehend and easy to maintain?
The answer is to use inheritance.
Object Oriented Programming - CoSc2051 4
Introduction to Inheritance
Super-classes and Sub-classes
Different classes may have some common properties and
behaviors:-
which can be generalized in a class that can be shared by other
classes.
You can define a specialized class that extends the generalized class.
The specialized classes inherit the properties and methods from the
general class.
In Java terminology, a class C1 extended from another class C2 is called
a subclass, and C2 is called a superclass.
Object Oriented Programming - CoSc2051 5
Introduction to Inheritance
Super-classes and Sub-classes
A superclass is also referred to as a parent class or a base class, and a
subclass as a child class, an extended class, or a derived class.
A subclass inherits accessible data fields and methods from its
superclass and may also add new data fields and methods.
The keyword “extends” used to create inheritance in java.
Object Oriented Programming - CoSc2051 6
Introduction to Inheritance
.
Dog Cat
String name String name
int fleas int hairballs
String getName() String getName()
int getFleas() int getHairballs()
void spark() void spark()
using
inheritance
superclass Animal
String name
String getName() subclass
subclass void spark()
Dog Cat
int fleas int hairballs
int getFleas() int getHairballs()
Object Oriented Programming - CoSc2051 7
Introduction to Inheritance
Super-classes and Sub-classes
Note the following points regarding inheritance:
Contrary to the conventional interpretation, a subclass is not a subset of
its superclass.
In fact, a subclass usually contains more information and methods
than its superclass.
Private data fields in a superclass are not accessible outside the class.
Therefore, they cannot be used directly in a subclass.
They can, however, be accessed/mutated through public accessors or
/mutators if defined in the superclass.
Not all is-a relationships should be modeled using inheritance.
Object Oriented Programming - CoSc2051 8
Recap
1. True or false? A subclass is a subset of a superclass.
2. What keyword do you use to define a subclass?
3. What is single class?
Object Oriented Programming - CoSc2051 9
Introduction to Inheritance
Using the super Keyword
The keyword super refers to the superclass and can be used to invoke
the superclass’s methods and constructors.
A subclass inherits accessible data fields and methods from its superclass.
The keyword super refers to the superclass of the class in which super
appears.
It can be used in two ways:
To call a superclass constructor.
To call a superclass method.
To call superclass method we use super.method(parameters);
Object Oriented Programming - CoSc2051 10
Introduction to Inheritance
Using the super Keyword
Calling Superclass Constructors:
A constructor is used to construct an instance of a class.
Unlike properties and methods, the constructors of a superclass are not
inherited by a subclass.
They can only be invoked from the constructors of the subclasses using
the keyword super.
The syntax to call a superclass’s constructor is:
super(), or super(parameters);
public ClassName() {
public ClassName() {
super();
// some statements Equivalent
// some statements
}
}
Object Oriented Programming - CoSc2051 11
Introduction to Inheritance
public class Rectangle {
double width;
Calling Superclass Constructors:
double length;
A constructor is used to construct an instance of a class.
// constructor used when no dimensions specified
Unlike {properties and methods, the constructors of a superclass are
Rectangle()
width = -1; // use -1 to indicate an uninitialized
not inherited by a subclass.
length = -1;
} can only be invoked from the constructors of the subclasses
They
// constructor used when all dimensions specified
using the
Box(double keywordl)super.
w, double {
width = w; length = l;
} The syntax to call a superclass’s constructor is:
// compute and return volume
super(), or super(parameters);
double area() {
return width * length;
}
}
Object Oriented Programming - CoSc2051 12
Introduction to Inheritance
public class Box {
// BoxWeight now uses super to initialize its Box attributes.
public class Cuboid extends Rectangle{
double width;
Calling Superclass Constructors:
double height;
double height; // weight of box
Adepth;
double constructor is used to construct an instance of a class.
// default
Unlikeconstructor
properties and no
methods, the constructors
// constructor used when dimensions specified of a superclass are
Cuboid() {
Box() {
not inherited by a subclass.
super();
width = -1; // use -1 to indicate
height = -1;
height = -1; // an uninitialized
} They can only be invoked from the constructors of the subclasses
depth = -1; // box
} using the keyword super.
// initialize width, height, and depth using super()
// constructor used when all dimensions specified
Cuboid(double
The syntaxw, double
to call l, double h) {constructor is:
a superclass’s
Box(double w, double h, double d) {
super(w, l); // call superclass constructor
width = w; height = h; depth = d;
height = h; or super(parameters);
super(),
}
}
// compute and return volume
}
double volume() {
return width * height * depth;
}
} Object Oriented Programming - CoSc2051 13
Introduction to Inheritance
public
public class
class Box {
TestDemoSuper {
double
public width;
Calling Superclass
static Constructors:
void main(String[] args) {
double height;
double Adepth;
Cuboid constructor
cb is used to20,
= new Cuboid(10, construct
15); an instance of a class.
Cuboid cb2= new Cuboid(); // default
Unlike properties
// constructor used whenand no
methods,
dimensionsthe constructors
specified of a superclass are
Box()
double{ vol;
not inherited by a subclass.
width = -1; // use -1 to indicate
vol= cb.volume();
height
They can =only
-1;be// an uninitialized
invoked from the constructors of the subclasses
depth = -1; // box of mybox1 is " + vol);
System.out.println("Volume
using the keyword super.
}System.out.println();
// constructor used when all dimensions specified
The syntax
Box(double w, doubleto call a superclass’s
h, double d) { constructor is:
vol = cb2.volume();
width = w; height = of
System.out.println("Volume h; cb2depth is =" d;+ vol);
super(),
}System.out.println();
or super(parameters);
// compute} and return volume
double
} volume() {
return width * height * depth;
}
} Object Oriented Programming - CoSc2051 14
Introduction to Inheritance
Types of Inheritance in Java
Object Oriented Programming - CoSc2051 15
Introduction to Inheritance
Single level Inheritance in Java
In single inheritance, one class inherits the properties of another.
It enables a derived class to inherit the properties and behavior from a
single parent class.
This will, in turn, enable code reusability as well as add new features to
the existing code.
Cat Extends Animal
Object Oriented Programming - CoSc2051 16
Introduction to Inheritance
Single level Inheritance in Java
class Animal {
public void eat(){System.out.println(“eating”);
In single} inheritance, one class inherits the properties of
}
another.
class Dog extends Animal {
void bark(){
It enables a derived class to inherit the properties and
System.out.println(“barking”);
}
behavior
} from a single parent class.
class TestInheritance {
This
publicwill, in turn,
static enable
void code reusability
main(String args[]) { as well as add new
Dog d = new Dog();
featuresd.bark();
to the existing code.
d.eat();
}
} Extends
Object Oriented Programming - CoSc2051 17
Introduction to Inheritance
Multi-level Inheritance in Java
When a class is derived from a class which is also derived from another
class, i.e. a class having more than one parent class but at different levels,
such type of inheritance is called Multilevel Inheritance.
Extends Extends
Puppy Dog Animal
Object Oriented Programming - CoSc2051 18
Introduction to Inheritance
Multi-level Inheritance in Java
class Animal {
void eat(){
System.out.println(“eating…”);}
}
class Dog extends Animal {
void bark(){
System.out.println(“barking…”);}
}
class Puppy extends Dog {
void weep(){
System.out.println(“weeping…”);}
}
Extends Extends
class TestInheritance2 {
Dog Animal
public static void main(String args[]) {
Puppy d = new Puppy();
d.weep();
d.bark();
d.eat();
} }
Object Oriented Programming - CoSc2051 19
Introduction to Inheritance
Recap
RULE 1: Multiple Inheritance is NOT permitted in Java.
RULE 2: Cyclic Inheritance is NOT permitted in Java.
RULE 3: Private members do NOT get inherited.
RULE 4: Constructors cannot be Inherited in Java.
RULE 5: In Java, we assign parent reference to child objects.
RULE 6: Constructors get executed because of super() present in the
constructor.
Object Oriented Programming - CoSc2051 20
Method Overriding and Overloading
Method Overriding
Re defining the method of the Super Class in the Sub Class.
Inheritance in java involves a relationship between parent and child
classes.
Whenever both the classes contain methods with the same name and
arguments or parameters it is certain that one of the methods will
override the other method during execution.
Method will be called depending on the object.
Method overriding is achieved in Inheritance.
Object Oriented Programming - CoSc2051 21
Method Overriding and Overloading
Method Overriding
class super {
public void display() {
System.out.println(“Hello”);
}
}
class sub extends super {
public void display() {
System.out.println(“Hello Welcome”);
}
}
The same method display() in super and sub class
Object Oriented Programming - CoSc2051 22
Method Overriding and Overloading
Method Overriding
When the sub class object is called then the display() method
inherited from the super class is shadowed and the sub class
display() method is executed.
Super Class method never be called upon the object of Sub Class.
In the given example program the super class have a method called
display() which is saying hello and another class sub class is taken where
it inherits the display() method from super class and re defines the
method.
Object Oriented Programming - CoSc2051 23
Method Overriding and Overloading
Method Overriding
Do’s and Don’ts of Overriding.
Signature must be same in method overriding.
If the method parameter is different the method is not overridden
but it is overloaded.
Return type must be same, if it is not same then the method is
neither overridden nor overloaded.
Final and static methods cannot be overridden.
Method can be overridden with same (public, protected,private) access
specifiers but the stricter(private) access specifiers cannot be used in sub
class.
Object Oriented Programming - CoSc2051 24
Method Overriding and Overloading
Method Overloading
Overloading methods enables you to define the methods with the same name
as long as their signatures are different.
Although we can overload static methods, the arguments or input
parameters have to be different.
We cannot overload two methods if they only differ by a static keyword.
Like other static methods, the main() method can also be overloaded.
Method(X)
Same class
Method(X,Y)
• You can have this three method in
Method(X,Y, Z)
single class
Object Oriented Programming - CoSc2051 25
Method Overriding and Overloading
Method Overloading
//method overloading
It is compile-time polymorphism.
public int max(double num1, double num2) {
if (num1 > num2) {
return num1;
} else {
return num2;
}
}
public int max(int num1, int num2,int num3) {
if (num1 > num2 && num1>num3) {
return num1;
} else if (num2>num3){
return num2;
}
else {return num3;}
}
Object Oriented Programming - CoSc2051 26
Method Overriding and Overloading
Method Overloading
Overloading methods can make programs clearer and more readable.
Methods that perform the same function with different types of
parameters should be given the same name.
Overloaded methods must have different parameter lists.
You cannot overload methods based on different modifiers or return
types.
Sometimes there are two or more possible matches for the invocation of
a method, but the compiler cannot determine the best match. This is
referred to as ambiguous invocation.
Ambiguous invocation causes a compile error.
Object Oriented Programming - CoSc2051 27
Method Overriding and Overloading
Method Overloading Tips
Consider the following code:
public class AmbiguousOverloading {
public static void main(String[] args) {
System.out.println(max(1, 2));
ambiguous
}
public static double max(int num1, double num2) {
invocation
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
}
Object Oriented Programming - CoSc2051 28
Method Overriding and Overloading
Difference between Method Overloading and Method Overriding
Method Overloading Method Overriding
It is used to increase the readability of the Provides a specific implementation of the
program method already in the parent class
It is performed within the same class It involves multiple classes
Parameters must be different in case of Parameters must be same in case of
overloading overriding
Is an example of compile-time
It is an example of runtime polymorphism
polymorphism
Return type must be same in overriding
Overriding does not involve static
Static methods can be overloaded
methods.
Object Oriented Programming - CoSc2051 29
Polymorphism
Assuming different forms. “Poly” means numerous, and “Morphs”
means forms.
Polymorphism means that a variable of a supertype can refer to a
subtype object.
Polymorphism in OOP is the ability of an object to take several forms.
Polymorphism literally means “being able to assume different forms.”
Polymorphism is an important and powerful concept in OOP.
It is the ability to process objects in a hierarchy differently depending on
their actual class type.
Object Oriented Programming - CoSc2051 30
Polymorphism
Polymorphism just means that different objects can respond to the
same message in different ways.
Polymorphism can work for both variables/states and
methods/behaviors of objects.
However, two powerful polymorphic concepts are often useful when you
define a class: (Types of Polymorphism-)
method overloading and method overriding.
or Compile-time and Run-time
Java implements polymorphism through method overloading and method
overriding.
Object Oriented Programming - CoSc2051 31
Polymorphism
Example:
The human body has different organs. Every organ has a different
function to perform;
class Shapes {
public void area() {
System.out.println("The formula for area of ");
}
}
class Triangle extends Shapes {
public void area() {
System.out.println("Triangle is ½ * base * height ");
}
}
class Circle extends Shapes {
public void area() {
System.out.println("Circle is 3.14 * radius * radius ");
}
} Object Oriented Programming - CoSc2051 32
Abstract Classes
There are two types of classes Abstract class and Concrete class.
An abstract class is a class that cannot be instantiated—we cannot create
instances of an abstract class.
One or more methods may be declared, but not defined.
(The programmer has not yet written code for a few methods).
The declared methods and classes have the keyword abstract in their
signature.
If abstract keyword is used before the class then it is an Abstract Class if
nothing is written before class then it is a Concrete class.
Reference of abstract class is allowed.
Object Oriented Programming - CoSc2051 33
Abstract Classes
Ways to achieve Abstraction in Java
The process of Abstraction in Java can be achieved by the following two
methods as mentioned below:
Implementing an Abstract Class
Implementing an Interface
The Syntax for Abstract Classes Abstract class may
have also
//a super abstract class non-abstract method
abtract class Super { which has a body
abstract void method();
}
Abstract class can include Abstract and Non-Abstract methods in them.
They can include constructors and static methods.
Object Oriented Programming - CoSc2051 34
Abstract Classes
//a super abstract class
abstract class Super {
Object of an Abstract class cannot be created but object of
Super() {
Concrete class can be created.
System.out.println(“Super”);
} abstract class and
abstract method
Reference of abstract
void meth1() { class is allowed.
System.out.println(“meth1”);
Example:
}
abstract void meeth2();
}
//concrete class
class sub extends Super {
Void meth2() {
System.out.println(“meth2”);
}
}
Object Oriented Programming - CoSc2051 35
Abstract Classes
class test {
public static void main() {
Super s1; // reference of abstract is allowed
sub s2 =new sub();
}
}
Object of an Abstract class cannot be created but object of Concrete class can be
created.
Reference of abstract class is allowed.
Example: Method which is not having a body is known as Abstract method, the
method must be declared as abstract.
The abstract method is undefined method. A class is Abstract class if at least one of
the methods is abstract.
Object Oriented Programming - CoSc2051 36
Abstract Classes
If any other class inherits abstract class then that class also
becomes abstract class but to become a concrete class the
subclass must override the abstract method of super class.
A class becomes useful if it overrides all the methods of
abstract class
Abstract classes are used for imposing standards and sharing
methods
Object Oriented Programming - CoSc2051 37
Abstract Classes
Do’s and Don’ts of Abstract Class
An Abstract class cannot be final because if it is made final then it
cannot be extended whereas abstract class is meant for
inheritance.
An Abstract method cannot be final because if it made final then it
cannot be overridden whereas Abstract method is meant for
overriding.
Abstract Class and method can neither be final nor static.
A Sub class must override an abstract method or else it will become
abstract class.
Object Oriented Programming - CoSc2051 38
Interfaces
Inheritance is used for borrowing methods.
Abstract is used for achieving polymorphism as well as Inheritance.
Inheritance is completely used for achieving Polymorphism.
Interface can be call as Abstract Class with all abstract methods.
All the methods are by default abstract.
Classes are extended but Interfaces are implemented.
In Interface we can have reference of interface and the object of the class
which is implemented.
Object Oriented Programming - CoSc2051 39
Interfaces
In java a class can extend from one class only but if a class is implementing
an interface then it can implement from multiple interfaces.
An interface in Java is a collection of abstract methods and static constants.
As you might know in an interface, each method is public and abstract but it
does not contain any constructor.
Along with abstraction, the interface also helps to achieve multiple
inheritance in Java.
Note:You can achieve 100% abstraction using interfaces.
Object Oriented Programming - CoSc2051 40
Interfaces
Interface
Example Program
interface test1 {
void meth1(); Collection of abstract
method
void meth2();
}
class test2 implements test1 {
public void meth1() {} Implementation of
abstract method in
public void meth2() {} derived class
}
class test {
public static void main(String[] args){ Creating an object derived
test1 t=new test2 (); class
t. meth1(); Calling method
} } Object Oriented Programming - CoSc2051 41
Interfaces
Do’s and Don’ts of Interfaces
By default, methods are Public and Abstract.
As methods are to be implemented by the classes, they can’t be made
private.
Identifiers can be used in interfaces but the identifiers must be given in
Upper cases.
Identifiers are by default final and static.
Method inside an interface cannot have body but the method can have
body if the method is static.
Static members can be accessed in main method by using interface name
and dot operator.
Object Oriented Programming - CoSc2051 42
Interfaces
Do’s and Don’ts of Interfaces
An interface can be extended from another interface.
Interface VS Multiple Inheritance
In C++ one class can inherit from multiple classes.
Multiple Inheritance in java is achieved using Interfaces.
Interfaces are perfect than using Multiple Inheritance.
Way of thinking in java is more perfect than C++.
Object Oriented Programming - CoSc2051 43
Interface vs Abstract Class
Interface Abstract Class
Can have Abstract and Non-Abstract
. Can have only Abstract Methods
Methods
It has only Final Variables It includes Non-Final Variables
It has Static, Non-Static, final, Non-
It has Static and Final variables only
Final variables
Will not implement the Abstract
Can implement an Interface
Class
Implemented using “implements” Implemented using “extends”
Keyword Keyword
Can extend Java Classes and
Can extend only an Interface
Interfaces
Members can be Private and
Members are Public by default
Protected
Object Oriented Programming - CoSc2051 44
Abstraction vs Encapsulation
Abstraction Encapsulation
. Solves the problem in the
Solves the problem in design level
implementation level
Encapsulation means hiding the
Used for hiding unwanted data and code and data into a single unit to
giving relevant results. protect data from the outside
world
Outer layout – used in terms of Inner layout – used in terms of
design implementation
Object Oriented Programming - CoSc2051 45
Bye
Take a look :
https://docs.oracle.com/en/java/
Object Oriented Programming - CoSc2051 46