Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views28 pages

Lecture - 5

The document provides an overview of polymorphism in Java, explaining its definition, types (static and dynamic), and related concepts such as late binding, abstract classes, and interfaces. It includes examples of polymorphism through class hierarchies and method overloading/overriding. Additionally, it outlines the rules for abstract classes and interfaces, emphasizing their roles in achieving encapsulation and code extensibility.
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)
6 views28 pages

Lecture - 5

The document provides an overview of polymorphism in Java, explaining its definition, types (static and dynamic), and related concepts such as late binding, abstract classes, and interfaces. It includes examples of polymorphism through class hierarchies and method overloading/overriding. Additionally, it outlines the rules for abstract classes and interfaces, emphasizing their roles in achieving encapsulation and code extensibility.
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
You are on page 1/ 28

Prepared by Bilew A.

1
Outline
✓Introduction

✓Polymorphic examples

✓Late Binding

✓Polymorphism Demonstrations

✓Abstract class

✓Final modifier

✓Introduction to Interface
Introduction Polymorphism
❖Polymorphism means "many forms", and it occurs when we have many classes
that are related to each other by inheritance.

❖Which keyword is used to call the superclass method in the overridden method?

super

❖Inheritance: lets us inherit attributes and methods from another class.


Polymorphism uses those methods to perform different tasks.

❖It enables us to write programs that process objects that share the same
superclass. This can simplify programming.

❖Polymorphism promotes extensibility:


Polymorphism examples
Animal(super class)
x-y coordinates
Move()

Frog Fish Bird


Move() Move() Move()
swim jum fly
Polymorphism examples
Quadrilateral (Super class)
L and w
Perimeter()
Area()

square trapezoid Rectangle parallelogram


Polymorphism examples
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 ");
}}
Polymorphism examples
class Main {
public static void main(String[ ] args) {
Shapes myShape = new Shapes(); // Create a Shapes object
Shapes myTriangle = new Triangle(); // Create a Triangle object
Shapes myCircle = new Circle(); // Create a Circle object
myShape.area();
myTriangle.area();
myShape.area();
myCircle.area();
}}
Types of Polymorphism
There are two types of Polymorphism.
1. Static polymorphism (or compile-time polymorphism)
▪ The methods use the same name but the parameter varies. This
represents the static polymorphism.
▪ method overloading allows compile-time polymorphism
▪ It decides which method to execute during compile time.
▪ N.B: In polymorphism, a reference variable of the superclass can refer
to the object of which classes?
The superclass or any of its subclasses.
Types of Polymorphism: Example:
class SimpleCalculator{
int add(int a, int b){
return a+b;
}
int add(int a, int b, int c){
return a+b+c;
}}
public class Demo{
public static void main(String args[ ])
{
SimpleCalculator obj = new SimpleCalculator();
System.out.println(obj.add(25, 25));
System.out.println(obj.add(25, 25, 30));
}}
Types of Polymorphism
2. Dynamic Polymorphism (or run time polymorphism in Java)
▪ The compiler doesn’t determine the method to be executed.
▪ It’s the JVM that performs the process at the run time.
▪ overriding method allows us to implement runtime polymorphism
▪ It happens among different classes as opposed to static polymorphism.
▪ Upcasting refers to the process where an object of the child class is
referred to by a reference variable of the superclass.
Types of Polymorphism: Example:
class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("walking safely with 30km");}
public static void main(String args[ ]){
Bike b = new Splendor(); //upcasting
b.run();
} }
Late and Early Binding
▪ Binding refers to the process of linking a method call to its corresponding
method implementation.

▪ Binding is divided in to two. These are early and Late binding.

▪ Early (static) Binding: The binding which can be resolved at compile time
by the compiler. Binding of all the static, private and final methods is done at
compile-time.

▪ Late (dynamic) binding: the compiler doesn’t decide the method to be


called. Example - Overriding. In overriding both parent and child classes
have the same method.
Early Binding Late Binding
It is a compile-time process It is a run-time process

The method definition and method call The method definition and method
are linked during the compile time. call are linked during the run time.

Actual object is not used for binding. Actual object is used for binding.

For example: Method overloading For example: Method Overriding

Program execution is faster Program execution is slower

Method overriding occurs when a subclass has the same method as the parent class.
Method Overloading means creating two methods with the same name and parameters but
different return types.
Abstract classes
➢Abstraction is a process of hiding the implementation details and
showing only functionality to the user.

The rules for the Java abstract class are:

➢An abstract class must be declared an abstract keyword

➢It can have abstract and non-abstract methods.

➢It cannot be instantiated.

➢It can have final methods

➢It can have constructors and static methods.


Abstract classes
➢They are used only as super classes in inheritance hierarchies, abstract
super classes.

➢Incomplete Subclasses must declare the “missing pieces.”

➢Main purpose is to provide an appropriate superclass from which other


classes can inherit and thus share a common design.

➢Classes that can be used to instantiate objects are called concrete classes.

➢Reduce client code’s dependencies on a range of specific subclass types.


Abstract Method
❖An abstract method serves as a placeholder for a method that will be fully
defined in a descendent class.

❖has a complete method heading with the addition of the modifier abstract.

❖It has no method body but does end with a semicolon in place of a method body.

❖ An abstract method cannot be private.

EXAMPLES

public abstract double getPay();

public abstract void doSomething( int count);


Final class and methods
The final method Modifier

➢adding the final modifier to the method heading.

➢ cannot be overridden with a new definition in a derived class.

public final void someMethod()


{ .
.
.

✓It means the compiler can use early binding with that particular method.
Final class and methods…
The final Class Modifier

Declaring entire class final cannot use it as a base class to derive


any other class from it.

public final class SomeClass

{ .

.
Introduction to java interfaces
➢It is a collection of abstract methods that define a set of behaviors that
a class must implement.

➢The primary purpose of interfaces is Achieve Encapsulation.

➢An interface also can define public named constants.

➢an interface should include comments.

➢A Java interface begins like a class definition, except that you use the
reserved word interface instead of class.

➢The interface can contain any number of public method headings.


Introduction to java interfaces…
▪ It contains no instance variables, however, nor any complete method definitions that is,
methods cannot have bodies.

▪ Benefit of using interfaces is to provide a clear contract for classes to follow.

SYNTAX
public interface Interface_Name {
Public_Named_Constant_Definitions
...
Public_Method_Heading_1;
...
Public_Method_Heading_n;
}
Abstract Classes implementing interfaces
➢A class that implements an interface must define a body for every
method that the interface specifies.

➢a class can implement more than one interface.

To implement an interface, a class must do two things:

1. Include the phrase

implements Interface_Name or

implements MyInterface, YourInterface


Abstract Classes implementing interfaces…
2. Define each method declared in the interface
❑ a class can implement multiple interfaces
For example, to implement the interface Measurable, a class Rectangle
must begin as follows:
public class Rectangle implements Measurable
❑ But, if the class is abstract the same applies to it.
public abstract class Rectangle implements Measurable {
// no mention of getPerimeter()and getArea() here
}
Abstract Classes implementing interfaces…
An Implementation of the Interface Measurable
public class Rectangle implements Measurable
{
private double myWidth;
private double myHeight;
public Rectangle(double width, double height)
{
myWidth = width;
myHeight = height;
}
public double getPerimeter() {
return 2 * (myWidth + myHeight); }
public double getArea() {
return myWidth * myHeight; } }
Derived interfaces
Extending an Interface

• Once you have an interface, you can define another interface that builds on,
or extends, the first one by using a kind of inheritance.

• Thus, you can create an interface that consists of the methods in an existing
interface plus some new methods.
For example, consider the classes of pets
public interface Nameable {
public void setName(String petName);
public String getName();
}
Derived interfaces…
We can extend Nameable to create the interface Callable:
public interface Callable extends Nameable
{
public void come(String petName);
}
You also can combine several interfaces into a new interface and
add even more methods if you like.
public interface Capable
{
public void hear();
public String respond();
}
Group assignment (5 students in 1 group)
▪ Analyze the different social media and identify the mostly used five among
the Ethiopian community. Using these social medias identify and analysis how
fake news, hate speech and etc.. that goes against the norm of the community.

▪ Using the above scenarios write a java program that could come with the
different ways of handling each of them.

▪ Your program should include every concepts we have learnt in the class.

▪ The concept must be analyzed by you and the identifiers should represent
their respective contents.
Questions
1. Define polymorphism
2. What are the types of Polymorphism in Java?
3. What is the primary purpose of interfaces in Java?
4. What is the keyword used to implement an interface in a class?
5. What is the difference between static and dynamic polymorphism?
6. What is the default access modifier of a method in an interface in
Java?
7. How many interfaces can a single class implement?
5/9/2025

You might also like