5/29/2023
Inheritance and Polymorphism
1
ObjectOriented Programming - CoSc2051
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
2
Object Oriented Programming - CoSc2051
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).
3
Object Oriented Programming - CoSc2051
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.
4
Object Oriented Programming - CoSc2051
2.
5/29/2023
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.
5
Object Oriented Programming - CoSc2051
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.
6
Object Oriented Programming - CoSc2051
Introduction to Inheritance
Object Oriented Programming - CoSc2051 7
Dog
String name
int fleas
String getName()
int getFleas()
void spark()
Cat
String name
int hairballs
String getName()
int getHairballs()
void spark()
Dog
int fleas
int getFleas()
Cat
int hairballs
int getHairballs()
Animal
String name
String getName()
void spark()
using
inheritance
superclass
subclass
subclass
.
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.
8
Object Oriented Programming - CoSc2051
3.
5/29/2023
Recap
1. True orfalse? A subclass is a subset of a superclass.
2. What keyword do you use to define a subclass?
3. What is single class?
9
Object Oriented Programming - CoSc2051
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);
10
Object Oriented Programming - CoSc2051
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);
11
Object Oriented Programming - CoSc2051
public ClassName() {
// some statements
}
public ClassName() {
super();
// some statements
}
Equivalent
Introduction to Inheritance
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);
12
Object Oriented Programming - CoSc2051
public class Rectangle {
double width;
double length;
// constructor used when no dimensions specified
Rectangle() {
width = ‐1; // use ‐1 to indicate an uninitialized
length = ‐1;
}
// constructor used when all dimensions specified
Box(double w, double l) {
width = w; length = l;
}
// compute and return volume
double area() {
return width * length;
}
}
4.
5/29/2023
Introduction to Inheritance
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);
13
Object Oriented Programming - CoSc2051
public class Box {
double width;
double height;
double depth;
// constructor used when no dimensions specified
Box() {
width = ‐1; // use ‐1 to indicate
height = ‐1; // an uninitialized
depth = ‐1; // box
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
// BoxWeight now uses super to initialize its Box attributes.
public class Cuboid extends Rectangle{
double height; // weight of box
// default constructor
Cuboid() {
super();
height = ‐1;
}
// initialize width, height, and depth using super()
Cuboid(double w, double l, double h) {
super(w, l); // call superclass constructor
height = h;
}
}
Introduction to Inheritance
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);
14
Object Oriented Programming - CoSc2051
public class Box {
double width;
double height;
double depth;
// constructor used when no dimensions specified
Box() {
width = ‐1; // use ‐1 to indicate
height = ‐1; // an uninitialized
depth = ‐1; // box
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
public class TestDemoSuper {
public static void main(String[] args) {
Cuboid cb = new Cuboid(10, 20, 15);
Cuboid cb2= new Cuboid(); // default
double vol;
vol= cb.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println();
vol = cb2.volume();
System.out.println("Volume of cb2 is " + vol);
System.out.println();
}
}
Introduction to Inheritance
Types of Inheritance in Java
15
Object Oriented Programming - CoSc2051
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.
16
Object Oriented Programming - CoSc2051
Cat Animal
Extends
5.
5/29/2023
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.
17
Object Oriented Programming - CoSc2051
Extends
class Animal {
public void eat(){System.out.println(“eating”);
}
}
class Dog extends Animal {
void bark(){
System.out.println(“barking”);
}
}
class TestInheritance {
public static void main(String args[]) {
Dog d = new Dog();
d.bark();
d.eat();
}
}
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.
18
Object Oriented Programming - CoSc2051
Animal
Dog
Extends
Puppy
Extends
Introduction to Inheritance
Multi-level Inheritance in Java
19
Object Oriented Programming - CoSc2051
Dog Animal
Extends
Extends
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…”);}
}
class TestInheritance2 {
public static void main(String args[]) {
Puppy d = new Puppy();
d.weep();
d.bark();
d.eat();
} }
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.
20
Object Oriented Programming - CoSc2051
6.
5/29/2023
Method Overriding andOverloading
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.
21
Object Oriented Programming - CoSc2051
Method Overriding and Overloading
Method Overriding
22
Object Oriented Programming - CoSc2051
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
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.
23
Object Oriented Programming - CoSc2051
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.
24
Object Oriented Programming - CoSc2051
7.
5/29/2023
Method Overriding andOverloading
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.
25
Object Oriented Programming - CoSc2051
Same class
Method(X)
Method(X,Y)
Method(X,Y, Z)
• You can have this three method in
single class
Method Overriding and Overloading
Method Overloading
26
Object Oriented Programming - CoSc2051
//method overloading
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;}
}
It
is
compile-time
polymorphism.
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.
27
Object Oriented Programming - CoSc2051
Method Overriding and Overloading
Method OverloadingTips
Consider the following code:
28
Object Oriented Programming - CoSc2051
public class AmbiguousOverloading {
public static void main(String[] args) {
System.out.println(max(1, 2));
}
public static double max(int num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
}
ambiguous
invocation
8.
5/29/2023
Method Overriding andOverloading
Difference between Method Overloading and Method Overriding
29
Object Oriented Programming - CoSc2051
Method Overriding
Method Overloading
Provides a specific implementation of the
method already in the parent class
It is used to increase the readability of the
program
It involves multiple classes
It is performed within the same class
Parameters must be same in case of
overriding
Parameters must be different in case of
overloading
It is an example of runtime polymorphism
Is an example of compile-time
polymorphism
Return type must be same in overriding
Overriding does not involve static
methods.
Static methods can be overloaded
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.
30
Object Oriented Programming - CoSc2051
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
Java implements polymorphism through method overloading and method
overriding.
31
Object Oriented Programming - CoSc2051
Compile-time and Run-time
Polymorphism
Example:
The human body has different organs. Every organ has a different
function to perform;
32
Object Oriented Programming - CoSc2051
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 ");
}
}
9.
5/29/2023
Typecasting in Java
One object reference can be typecast into another object reference.This is
called casting object.
In the preceding section, the statement
assigns the object new Student() to a parameter of the Object type.
This statement is equivalent to:
The statement Object o = new Student(), known as implicit casting, is legal
because an instance of Student is an instance of Object.
33
Object Oriented Programming - CoSc2051
m(new Student());
Object o = new Student(); // Implicit casting
m(o);
Typecasting in Java
Student b = (Student)o; // Explicit casting
It is always possible to cast an instance of a subclass to a variable of a
superclass (known as upcasting).
Type casting for primitive data type to another.
However, casting an object reference does not create a new object.
For example
34
Object Oriented Programming - CoSc2051
int age = 45;
// A new value is assigned to newAge
byte newAge = (byte)age;
Object o = new Circle();
Circle c = (Circle)o; // No new object is created
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.
35
Object Oriented Programming - CoSc2051
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 can include Abstract and Non-Abstract methods in them.
They can include constructors and static methods.
36
Object Oriented Programming - CoSc2051
//a super abstract class
abtract class Super {
abstract void method();
}
Abstract class may
have also
non-abstract method
which has a body
10.
5/29/2023
Abstract Classes
Objectof an Abstract class cannot be created but object of
Concrete class can be created.
Reference of abstract class is allowed.
Example:
37
Object Oriented Programming - CoSc2051
//a super abstract class
abstract class Super {
Super() {
System.out.println(“Super”);
}
void meth1() {
System.out.println(“meth1”);
}
abstract void meeth2();
}
//concrete class
class sub extends Super {
Void meth2() {
System.out.println(“meth2”);
}
}
abstract class and
abstract method
Abstract Classes
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.
38
Object Oriented Programming - CoSc2051
class test {
public static void main() {
Super s1; // reference of abstract is allowed
sub s2 =new sub();
}
}
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
39
Object Oriented Programming - CoSc2051
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.
40
Object Oriented Programming - CoSc2051
11.
5/29/2023
Interfaces
Inheritance isused 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.
41
Object Oriented Programming - CoSc2051
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.
42
Object Oriented Programming - CoSc2051
Interfaces
Example Program
43
Object Oriented Programming - CoSc2051
interface test1 {
void meth1();
void meth2();
}
class test2 implements test1 {
public void meth1() {}
public void meth2() {}
}
class test {
public static void main(String[] args){
test1 t=new test2 ();
t. meth1();
} }
Collection of abstract
method
Interface
Implementation of
abstract method in
derived class
Creating an object derived
class
Calling method
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.
44
Object Oriented Programming - CoSc2051
12.
5/29/2023
Interfaces
Do’s andDon’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++.
45
Object Oriented Programming - CoSc2051
Interface vs Abstract Class
.
46
Object Oriented Programming - CoSc2051
Abstract Class
Interface
Can have Abstract and Non-Abstract
Methods
Can have only Abstract Methods
It includes Non-FinalVariables
It has only FinalVariables
It has Static, Non-Static, final, Non-
Final variables
It has Static and Final variables only
Can implement an Interface
Will not implement the Abstract
Class
Implemented using “extends”
Keyword
Implemented using “implements”
Keyword
Can extend Java Classes and
Interfaces
Can extend only an Interface
Members can be Private and
Protected
Members are Public by default
Abstraction vs Encapsulation
.
47
Object Oriented Programming - CoSc2051
Encapsulation
Abstraction
Solves the problem in the
implementation level
Solves the problem in design level
Encapsulation means hiding the
code and data into a single unit to
protect data from the outside
world
Used for hiding unwanted data and
giving relevant results.
Inner layout – used in terms of
implementation
Outer layout – used in terms of
design
Bye
Take a look :
https://docs.oracle.com/en/java/
48
Object Oriented Programming - CoSc2051