Lec 07 - Polymorphism
Lec 07 - Polymorphism
Lecture 07
Polymorphism
16/07/2024
Bachelor of Science (Hons) in Computer Science | Software Engineering | Information Technology
Department of Computing
Faculty of Computing and Technology
Saegis Campus
Nugegoda
1
Lecturer Name Saegis Campus
Polymorphism
• It is a feature, which lets us create functions with same name but different arguments,
which will perform different actions.
• That means, functions with same name, but functioning in different ways.
• Or, it also allows us to redefine a function to provide it with a completely new definition.
2
T.L.Navodi Sithara Saegis Campus
Polymorphism
• Generally, polymorphism refers to the ability to appear in many forms.
3
T.L.Navodi Sithara Saegis Campus
Example
4
T.L.Navodi Sithara Saegis Campus
Method signatures
• Signatures consist of the function name and the type and order of its
parameters.
• Examples:
setExam(int)
getCoursework()
5
T.L.Navodi Sithara Saegis Campus
Method Overloading
• If you have two methods with same name in one Java class with different method signature
then its called an overloaded method.
• Have different set of arguments to perform something based on different number of input.
• Binding of overloading method occurs during compile time and overloaded calls resolved using
static binding. (Also known as Early binding)
• Just remember in order to change signature you either need to change number of argument,
type of argument or order of argument in Java if they are of different types.
6
T.L.Navodi Sithara Saegis Campus
Three ways to overload a method
1.Number of parameters.
▪add(int, int)
▪add(int, int, int)
2.Data type of parameters.
▪add(int, int)
▪add(int, float)
3. Sequence of Data type of parameters
▪add(int, float)
▪add(float, int)
7
T.L.Navodi Sithara Saegis Campus
Constructor Overloading
• Consider the constructors in the Marks class:
• Marks() - has no parameters (initialises both attributes with -1, i.e. no
mark recorded)
• Marks(int, int) has two parameters, one for each attribute.
• There are two constructors, same function name but different signatures.
8
T.L.Navodi Sithara Saegis Campus
Method Overriding
• Overridden methods have the same method signature & only the method body is
different in sub classes.
• Method overriding forms the basis for one of Java’s most powerful concepts:
Dynamic method dispatch
9
T.L.Navodi Sithara Saegis Campus
Polymorphism in OOP
• The most common use of polymorphism in OOP occurs when a
parent class reference is used to refer to a child class object.
Animal a =new Dog ();
10
T.L.Navodi Sithara Saegis Campus
Example-Method Overloading
11
T.L.Navodi Sithara Saegis Campus
Example-Method Overloading
12
T.L.Navodi Sithara Saegis Campus
Example-Method Overriding
13
T.L.Navodi Sithara Saegis Campus
Example-Method Overriding
14
T.L.Navodi Sithara Saegis Campus
15
Lecturer Name Saegis Campus