0% found this document useful (0 votes)
42 views46 pages

Inheritance and Polymorphism in Java

The document covers key concepts of inheritance and polymorphism in object-oriented programming, particularly in Java. It explains the definitions and advantages of inheritance, the differences between method overloading and overriding, and the use of abstract classes and interfaces. Additionally, it discusses runtime polymorphism and the role of the 'super' keyword in accessing parent class methods and variables.

Uploaded by

alemma688
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)
42 views46 pages

Inheritance and Polymorphism in Java

The document covers key concepts of inheritance and polymorphism in object-oriented programming, particularly in Java. It explains the definitions and advantages of inheritance, the differences between method overloading and overriding, and the use of abstract classes and interfaces. Additionally, it discusses runtime polymorphism and the role of the 'super' keyword in accessing parent class methods and variables.

Uploaded by

alemma688
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

Bule Hora University

College of Informatics
Department of Computer Science

CoSc2052: Object Oriented Programming

Chapter 3:
Inheritance and Polymorphism

Nigussu B.
[Link]@[Link]

1
Inheritance
• Inheritance is one of the cornerstones of object-
oriented programming
• because it allows the creation of hierarchical
classifications
• a class that is inherited is called a superclass.
• The class that does the inheriting is called a subclass
• A subclass inherits all of the instance variables and
methods defined by the superclass and adds its own,
unique elements
• Advantages of Inheritance
– reuse
– enhancement,
– adaptation, etc
2
• Two ways of expressing relationships
– Generalization/Specialization
• ‘is a” relationship
– Example: Circle is a shape

– Whole-part
• Part of or “has a” relationship
– Example: Employee class has a BirthDate class

• Called aggregation

• Inheritance Creates an is-a relationship

3
Superclass
Shape

Subclass
3D_Shape 2D_Shape

Subclass
Sphere Cube Rectangle Circle Triangle

Above: is-a
Circle is a 2D_Shape
below: has-a
Employee has a date
Employee Date
firstName day
lastName month
Birthdate year
Hiredate
4
• Inheritance Basics
– To inherit a class, you simply incorporate the
definition of one class into another by using the
extends keyword
– The general form is:
Class SubClassName extends SuperClassName
{
// body of class
}
– Java does not support the multiple inheritance
– Subclasses cannot access private members

5
Example1

6
Example 2

7
Types of inheritance in java

8
Cont’d

9
Single Inheritance Example

10
Multilevel Inheritance Example

11
Hierarchical Inheritance Example

12
Final Classes – Preventing Inheritance
• Sometimes you will want to prevent a class from
being inherited.
• To do this, precede the class declaration with
final.

13
Method Overloading in Java
• If a class has multiple methods having same name
but different in parameters, it is known as Method
Overloading.
• If we have to perform only one operation, having
same name of the methods increases the
readability of the program.
• There are two ways to overload the method in
java
• By changing number of arguments
• By changing the data type

14
Method Overloading: changing no. of
arguments

15
Method Overloading: changing data type of
arguments

16
Method Overriding in Java
• If subclass (child class) has the same method as
declared in the parent class, it is known as method
overriding in java.
• In other words, If subclass provides the specific
implementation of the method that has been
provided by one of its parent class, it is known as
method overriding.
• Usage of Java Method Overriding
• Method overriding is used to provide specific
implementation of a method that is already
provided by its super class.
• Method overriding is used for runtime
polymorphism 17
Cont’d
• Rules for Java Method Overriding
• method must have same name as in the parent
class
• method must have same parameter as in the
parent class.
• must be IS-A relationship (inheritance).

18
Example of method overriding

Output:Bike is running safely


19
Cont’d
// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
[Link]("i and j: " + i + " " + j);
}
}

20
class B extends A {
int k; The output
B(int a, int b, int c) { k: 3
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
[Link]("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
[Link](); // this calls show() in B
}
}

21
• If you wish to access the superclass version of an
overridden function, you can do so by using super.
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
[Link](); // this calls A's show()
[Link]("k: " + k);
}
}
• output:
– i and j: 1 2 k: 3

22
Overloading vs. Overriding
• Don't confuse the concepts of overloading and
overriding
• Overloading deals with multiple methods with the
same name in the same class, but with different
signatures
• Overriding deals with two methods, one in a parent
class and one in a child class, that have the same
signature
• Overloading lets you define a similar operation in
different ways for different data
• Overriding lets you define a similar operation in
different ways for different object types
23
super keyword in java
• The super keyword in java is a reference variable
which is used to refer immediate parent class object.
• Whenever you create the instance of subclass, an
instance of parent class is created implicitly which is
referred by super reference variable.
• Usage of java super Keyword
• super can be used to refer immediate parent class
instance variable.
• super can be used to invoke immediate parent class
method.
• super() can be used to invoke immediate parent class
constructor.
24
Cont’d

25
Polymorphism
• Polymorphism in java is a concept by which we can
perform a single action by different ways.
• Polymorphism is derived from 2 greek words: poly
and morphs.
• The word "poly" means many and "morphs" means
forms. So polymorphism means many forms.
• There are two types of polymorphism in java:
compile time polymorphism and runtime
polymorphism.
• We can perform polymorphism in java by method
overloading and method overriding.
26
Runtime Polymorphism in Java
• Runtime polymorphism or Dynamic Method
Dispatch is a process in which a call to an
overridden method is resolved at runtime rather
than compile-time.
• In this process, an overridden method is called
through the reference variable of a superclass.
• The determination of the method to be called is
based on the object being referred to by the
reference variable.

27
Upcasting
• When reference variable of Parent class refers to
the object of Child class, it is known as upcasting.
For example:

28
Example of Java Runtime Polymorphism
• In this example, we are creating two classes Bike
and Bike1. Bike1 class extends Bike class and
overrides its run() method.
• We are calling the run method by the reference
variable of Parent class. Since it refers to the
subclass object and subclass method overrides the
Parent class method, subclass method is invoked at
runtime.
• Since method invocation is determined by the JVM
not compiler, it is known as runtime
polymorphism.
29
Cont’d
• 1. class Bike{
• 2. void run(){[Link]("running");}
• 3. }
• 4. class Bike1 extends Bike{
• 5. void run(){[Link]("running safely
with 60km");}
• 6.
• 7. public static void main(String args[]){
• 8. Bike b = new Bike1();//upcasting
• 9. [Link]();
• 10. }
Output: running safely with 60km.
• 11. }
30
// Dynamic Method Dispatch
class A {
void callme() {
[Link]("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
[Link]("Inside B's callme method");
}
}

31
class C extends A {
// override callme()
void callme() {
[Link]("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
[Link](); // calls A's version of callme
r = b; // r refers to a B object

32
[Link](); // calls B's version of callme
r = c; // r refers to a C object
[Link](); // calls C's version of callme
}
}
• The output from the program is shown here:
Inside A's callme method
Inside B's callme method
Inside C's callme method

33
Abstraction
• Abstraction as the process of hiding internal details
of implementation and only showing essential
functionality things to the user.
• It is a process where you show only “relevant” data
and “hide” unnecessary details of an object from
the use.
• It is the process of gaining information.
• An abstract class is defined as a class that’s
declared with the “abstract” keyword. It is a
collection of common subclass characteristics that
should include at least one abstract method. An
abstract class can have multiple concrete methods 34
Cont’d
• An abstract class cannot be instantiated, meaning
cannot create an object with it like normal class.

35
Cont’d
• but, you can instantiate/create object from other
Class, and using this instance/object you can access
all the fields and methods of Abstract class.

36
Cont’d
• To use an abstract class, you have to inherit it.
Meaning abstract class may have subclass.

37
Abstract Methods
• abstract keyword is used to declare the method as
abstract.
• You have to place the abstract keyword before the
method name in the method declaration.
• An abstract method contains a method signature, but no
method body.
• Instead of curly braces, an abstract method will have a
semi colon (;) at the end.

38
Interface
• An interface is a blueprint used to implement a
class.
• It is a collection of abstract methods and contains
no concrete methods, unlike abstract class.
• Like a class, an interface can contain methods and
variables, though the declared methods default to
abstract.
• Interfaces cannot be instantiated/create object

39
Cont’d
Programmers use interface when they need:
• To achieve abstraction
• To support a dynamic resolution at run time
• Achieving loose coupling
• Separating a method’s definition from the
inheritance’s hierarchy

40
Abstract class Vs Interface
• Abstract class and interface both are used to achieve
abstraction where we can declare the abstract methods.
Abstract class and interface both can't be instantiated.

41
42
43
44
Multiple inheritance by Interface in Java

45
Cont’d
• Interface used the keyword to inherit instead of extends
‘implements’.
• The interface AnimalEat and AnimalTravel have one
abstract method each i.e. eat() and travel(). The class Cat
implements the interfaces AnimalEat and AnimalTravel.
• In the method main() in class Demo, an object a of class
Cat is created. Then the methods eat() and travel() are
called.
• Cat class inherited through interface AnimalEat and
AnimalTravel .

46

You might also like