You are on page 1of 23

Lecture 07

Chapter 5
Polymorphism and Interfaces

By: Mequanent Argaw


Debre Markos University

12/11/2015 Department of ECE, College of Technology 1


Lecture Outline
 Introduction to Polymorphism

 Basis for polymorphism

 Implementation of Polymorphism

 Abstract Classes

 Using the keyword final

 Interface
12/11/2015 Department of ECE, College of Technology 2
Introduction to Polymorphism
 One of the most powerful benefits of inheritance is that, it allows a

client code to treat different kinds of objects in the same way.

 The ability for the same code to be used with several different types

of objects and for that code to behave differently depending on the

actual type of object used is called Polymorphism.

 “Polymorphism” comes from the Greek words “poly” (many) +

“morph” (form)

12/11/2015 Department of ECE, College of Technology 3


Basis for Polymorphism
Polymorphism is a powerful feature built on top of inheritance hierarchies

through the following two concepts:


 Subtyping and

 Method Overriding

Polymorphism is made possible by the fact that the type of a reference variable(

one that refers) to an object does not have to exactly match the type of object it

refers to.

The ability for superclass variables to refer to subclass objects allow us to write

flexible code that can interact with many type of objects in the same way.

12/11/2015 Department of ECE, College of Technology 4


Basis for Polymorphism cont…
 In addition to sub typing, method overriding forms the
basis for one of Java’s most powerful concepts: dynamic
method dispatch.
 Dynamic method dispatch is the mechanism by which a
call to an overridden method is resolved at run time
rather than compile time.
 Dynamic method dispatch is how Java implements run-
time polymorphism.
12/11/2015 Department of ECE, College of Technology 5
How is polymorphism implemented?
Java uses Subtyping to resolve calls to overridden methods at run time. Here is

how:

When an overridden method is called through a superclass reference, Java

determines which version of that method to execute based upon the type of the

object being referred to at the time the call occurs.

When different types of objects are referred to, different versions of an

overridden method will be called.

It is the type of the object being referred to (not the type of the reference

variable) that determines which version of an overridden method will be

executed.

12/11/2015 Department of ECE, College of Technology 6


Example
class Sup{ class DynDispDemo{
void who(){
public static void main(String[] args){
System.out.println(“who() in Sup”);
Sup superob = new Sup();
}
Sub1 subob1 = new Sub1();
}
Sub2 subob2 = new Sub2();

t?
class Sub1 extends Sup{

pu
void who(){

t
ou
Sup supRef;
System.out.println(“who() in Sub1”);

he
supRef = superob;
}

et
supRef.who();

b
}

ill
supRef = subob1;

tw
class Sub2 extends Sub1{
supRef.who();

ha
void who(){
supRef = subob2;

W
System.out.println(“who() in Sub2”);
supRef.who();
}
}
}
}

12/11/2015 Department of ECE, College of Technology 7


Why Polymorphism
 Polymorphism is essential to object-oriented
programming for one reason:
 It allows a general class to specify methods that will be common
to all of its derivatives, while allowing subclasses to define the
specific implementation of some or all of those methods.

 Overridden methods allow Java to implement the “ one interface,


multiple methods” aspect of polymorphism.

12/11/2015 Department of ECE, College of Technology 8


Introduction to Abstract Classes
Sometimes you will want to create a superclass that defines only a
generalized form that will be shared by all of its subclasses leaving
out the details to the subclasses.

Such a class determines the nature of the methods that the subclasses
must implement but does not provide an implementation itself.

This happens when a superclass is unable to create a meaningful


implementation for a method.

e.g. the getArea() method in Shape class.

12/11/2015 Department of ECE, College of Technology 9


Introduction to Abstract Classes…
You can handle such situations in two ways:

1. You can make the method in the superclass to simply report a warning

message

While this approach can be useful sometimes, it is not usually appropriate.

In cases where you want to ensure that a subclass does, indeed, override all

necessary methods in the superclass you should provide an appropriate

mechanism
2. Provide an abstract method in place of the method to be overridden.

12/11/2015 Department of ECE, College of Technology 10


Creating abstract methods
Created by specifying the abstract type modifier.

An abstract method is a method which contains no body and hence is

not implemented in the class it is declared.

If a superclass provides an abstract method its subclass method must

override it – it can not use the version defined in the superclass.

To declare an abstract method use the following syntax form:


 abstract return-type name(parameter-list);

The abstract modifier can not be used with static methods or

constructors.
12/11/2015 Department of ECE, College of Technology 11
What is an abstract class ?
An abstract class is a class that contains one or more abstract methods in its definition.

To declare a class as an abstract class add the abstract modifier before the keyword class

in the class declaration header.

Use the following syntax in the class definition:

abstract class classname {

//define your abstract methods, and fields here

Note: if you create your superclass as an abstract class


 You must always define at least one abstract method inside the abstract class .

 You must always override that abstract method in all of your subclasses that extend the

superclass.

12/11/2015 Department of ECE, College of Technology 12


Using final
 As powerful and useful are method overriding and inheritance sometimes

you might to prevent their use.

 Whatever the reasons, in Java it is possible to prevent a method from

being overridden or a class from being inherited by using the keyword

final.

 To prevent a method from being overridden, specify final as a modifier at

the start of its declaration. Methods declared as final cannot be

overridden.

 You can prevent a class from being inherited by preceding its declaration with final.

12/11/2015 Department of ECE, College of Technology 13


final Prevents Overriding and Inheritance
final class A {
class A { // ...
final void meth() {
System.out.println("This is a
}
final method."); // The following class is illegal.
} class B extends A { // ERROR! Can't
extend from class A
} // ...
class B extends A {
}
void meth() {
// ERROR! Can't override.
System.out.println("Illegal!");
}
}

12/11/2015 Department of ECE, College of Technology 14


Interface:
Why it is needed?
Inheritance is useful because it enables polymorphism and code

sharing but it does have several limitations:


1. Java only supports single inheritance, so it is impossible to setup multiple

is-a relationships for classes that share multiple characteristics.

2. There are also situations in which you want is-a relationships and

polymorphism but you do not want to share code.

Solution:
 Java provides a feature called Interface that can represent a common

supertype between several classes without code sharing.


12/11/2015 Department of ECE, College of Technology 15
What is an Interface ?
 Interfaces define and standardize the ways in which things

such as people and systems can interact with one another.

 E.g. the controls on a radio serve as an interface between

radio users and a radio’s internal components.

 The control allows users to perform a set of operations.

 The interface specifies what operations a radio must permit users to

perform but does not specify how the operations are performed.

12/11/2015 Department of ECE, College of Technology 16


Interface in Software
Java provides a mechanism that allows you to declare an abstract data

type(similar to a class) that consist of a set of method declarations without their

implementations.

An interface is like a class, but it contains only method headers without bodies.

However, an interface does not have instance fields but can contain

variables(more on this later…)

A class can use an interface by promising to implement the interface, meaning that

the class promises to provide implementations of all the methods that are

declared in the interface.

Classes that implement an interface form an is-a relationship with that interface.

12/11/2015 Department of ECE, College of Technology 17


Creating an Interface: Declaration
Syntax
Syntax:

public interface InterfaceName{

method signatures

}
rov ided
is p
n t at io n
p leme
No im
E.g.

public interface Measurable{

double getMeasure();
n interface
The method of a
}

Department of ECE, College of


12/11/2015 18
Technology
Details about Interface Declarations
To create an interface, we create a new file with the same name as the interface’s name.

The file will have the .java extension.

We give the interface a header with the keyword interface in place of the keyword class
 E.g. public interface Shape {

// …}

All interfaces are declared either as public or without an access modifier( in this case

the interface will only be available to classes inside the same package as the interface).

Methods in an interface are declared using only their return type and signature. They

are implicitly public and abstract.

Variables declared in an interface are not instance variables. Instead they are implicitly

public, final and static and must be initialized.

12/11/2015 Department of ECE, College of Technology 19


Differences between Interfaces and Classes

 An interface type is similar to a class, but there are


several important differences:

1. All methods in an interface type are abstract; i.e. they


have a name, parameters and a return type, but they
do not have an implementation.

2. All methods in an interface are automatically public.

3. An interface type does not have instance variables.

12/11/2015 Department of ECE, College of Technology 20


Implementing Interfaces
 Once an interface has been defined, one or more
classes can implement that interface.
 To implement an interface, include the keyword
implements followed by the interface name in the
class definition.
 Create all methods declared by the interface inside
the body of the class that implements the interface.
12/11/2015 Department of ECE, College of Technology 21
Implementing Interfaces: Example
Syntax:
public class ClassName implements InterfaceName, InterfaceName, …
{
that this
List all interface types
instance variables
a nk A ccount
methods B class implements.
instance
} s
variable
E.g.
public class BankAccount implements Measurable{
….
public double getMeasure(){ n tat io n
pl eme e.
return balance;
s t he im intefac
} p rovide d in the
Ba Oth e t hod
declare
m
This e method
…. nk
A er
h
} me cc
th oun for t
od t
s
12/11/2015 Department of ECE, College of Technology 22
Using Interface References
 An interface is just another kind of specifying an
abstract data type.
 So do not be surprised to learn that you can
declare a reference variable of an interface type.
 The only thing you are not allowed to do is
instantiate an object of an interface type.

12/11/2015 Department of ECE, College of Technology 23

You might also like