Chapter Five
Polymorhism
By: Biruk M.
1
outline
Methods
Call by value/reference?
Interface
Multiple methods in interface
Multiple interface
Polymorphism
overloading
Overriding
Referenceing of classes
Abstract class
abstract methods
2
Method
A Java method is a collection of statements that are
grouped together to perform an operation.
Eg:- When you call the System.out.println() method,
the system actually executes several statements in order to display a
message on the console.
Syntax
public static int methodName(int a, int b) {
// body
}
Or
modifier returnType nameOfMethod (Parameter List) {
// method body
}
3
examples Passing Parameters by Value means
calling a method with a parameter.
Through this, the argument value is
public static int minFunction(int n1, passed to the parameter.
int n2) { The values of the arguments remains the
same even after the method invocation.
int min;
Example
if (n1 > n2)
min = n2; Public static void main(String
args[])
else { int x=10,y=20;
min = n1; Value of x and y?
S.O.P(add(x,y))
Value of x and y?
return min; }
} Public static int add(int x,int y)
{x=x+3;
Y=y+5;
Return (x+y);
}
Can we use passing by Reference in java?
How? 4
2. Interface
set of methods with signature and parameters but not
implemented only the class will implement in its own interest
An interface is a blueprint of class/ a contract for a class.
It has constants and abstract methods
interface gives 100% abstraction, so it is called fully abstraction.
An interface declaration consists of modifiers, the
keyword interface, the interface name, a comma-separated list of
parent interfaces (if any), and the interface body.
To declare a class that implements an interface, you include
an implements clause in the class declaration.
There is no executable body for any method that is left to each class
that implements the interface
Interface also represent IS-A relationship.
Why use interface?
It is use to achieve fully abstraction.
By using interface we achieve multiple inheritances. 5
Eg:-
Cont… public interface Hello {
Syntax: public String dispMsg() ;
The interface keyword is }
used to declare an Implementer class:
interface. public class MsgImp
public interface Interface- implements Hello {
name{ public String dispMsg()
//Any number of final, static fie {
lds return "Hello World!";
//Any number of abstract meth }
od declarations
public static void main(String
} args[]) {
MsgImp xx=new MsgImp();
System.out.println(xx.dispMsg())
;
}
}
6
Multiple methods in interface
public interface Sample {
public int sum(int x, int y) ;
Eg:- public int prod(int x, int y) ;
Interfaces may specify but do not }
implement methods.
public class SamImpl
A class that implements the implements sample {
interface must implement all its public int sum(int x, int y)
methods.
{ return x+y; }
If you want not to implement public int prod(int x, int y)
the methods u can use empty {return x*y; }
body for void functions or public static void main(String
return 0 for type-functions args[]){
public int sum(int x, int y) SamImpl xx=new SamImpl();
{ System.out.println(xx.sum(4,9));
return 0; System.out.println(xx.prod(4,9));
} }
}
7
public class MultipleInterface implements
Multiple interface Hello,Sample{
public String dispMsg()
Your class can implement more {
than one interface, so return "Hello World!";
}
the implements keyword is public int sum(int x, int y)
followed by a comma-separated {
return x+y;
list of the interfaces implemented
}
by the class. public int prod(int x, int y)
{
return x*y;
}
public static void main(String args[])
{
int x=10,y=5;
MultipleInterface xx=new MultipleInterface();
System.out.println(xx.dispMsg());
System.out.println(xx.prod(x,y));
System.out.println(xx.sum(x,y));
}}
8
Extending interface?
Eg:
An interface can extends
another interface like the way to interface Vehicle{
the class extends another class public void displayColor();
using extends keyword.
}
The child interface inheritance
the method and member interface Car extends Vehicle{
variable of parent interface. public void showMiledge();
By convention, }
the implements clause follows
the extends clause, if there is
one.
9
Multiple inheritance-interface class maindemo {
public static void main(String arg
interface car
s[]){
{int speed=90;
System.out.println("Vehicle");
public void distance();
Vechicle v1=new Vehicle();
}
v1.distance();
interface bus v1.speed();
{ int distance=100; }
public void speed();
}
}
class vehicle implements car,bus{
public void distance() Output?
{
int distance=speed*100;
System.out.println("distance travelle
d is"+distance);
}
public void speed() {
int speed=distance/100;}
10
}
3. Polymorphism
Polymorphism is achieved by redefining or
overriding routines. Be careful not to confuse
overriding and overloading.
Overloading arises when two or more functions share a name.
These are disambiguated by the number and types of the
arguments.
Overloading means the use of the same name in the same
context for different entities with completely different
definitions and types.
11
Cont…
How Polymorphism support in Java?
Java has excellent support of polymorphism in terms of method
overloading (compile time polymorphism) and method overriding
(runtime polymorphism).
Function overloading provides a way to have multiple
functions with the same name.( The compiler selects the
appropriate version. This process is called function resolution.)
Polymorphism:-
“many forms”, refers to identically named ,methods that have
different behavior depending on the type of the object they
refer.
Helps to design and implement systems that are more easily
extensible.
12
Method Overloading
Static Binding or compile time polymorphism
Early binding:-choosing the method in normal way during compilation
time
If a class have multiple methods by same name but different
parameter is known as Method Overloading.
appear in the same class or a subclass
have the same name but,
have different parameter lists, and,
can have different return types
Advantage of Method Overloading
Method overloading increases the readability of program.
How to overload method
There are two way to overload the method.
By changing number of arguments.
By changing the data type of arguments.
Note: In Java, Method overloading is not possible with changing
13
return type of methods.
Example:
public class Sample{
public void sum(int a, int b){
System.out.println(a+b);
}
public void sum(int a, int b, int c){
System.out.println(a+b+c);
}
public static void main(String args[]){
Sample st = new Sample();
st.sum(10,20);
st.sum(10,20,30);
}}
Check by changing Data types of arguments?
14
Method Overriding
Dynamic Binding or Runtime Polymorphism)
Having the same method in the subclass as declare in parent class
is known as method overriding.
object type (NOT reference variable type) determines which
overriden method will be used at runtime
overriding method MUST have the same argument list (if not, it
might be a case of overloading)
abstract methods MUST be overridden
final methods CANNOT be overridden
static methods CANNOT be overridden
constructors CANNOT be overridden
15
(cont’d)
Advantages of Method Overriding:
Time to invest method signature is reduced
Different functionality in both super class and sub class by sharing
same signature
The functionality can be enhanced
The behavior can be replaced in the sub class
Method Overriding is used for Runtime Polymorphism
16
Example void display(){
class superCls{ System.out.println("super y = " +y);
int y; System.out.println("sub z = " +z);
superCls(int y) { }
this.y=y;
} }
void display(){ public class Test{
System.out.println("super y = " +y); public static void main(String[] args){
} subCls obj1 = new subCls (500,300);
obj1.display();
}
}
class subCls extends superCls{
}
int z;
Look the overriding method?
subCls(int z , int y){
super(y);
this.z=z;
}
17
4. Abstract 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.
An abstract class can have both abstract and non-abstrac
t methods
Rule: An abstract class can have zero or more abstract
methods
Abstract methods need to be defined in concrete subclas
ses (classes that can be instantiated) 18
Example
public String getLastName(){
public abstract class Employee1 {
return lastName;
private String firstName;
private String lastName; }
public Employee1( String first, String public String toString(){
last ) { return firstName + ' ' + lastName;
firstName = first; }
lastName = last; public abstract double
} earnings();
public String getFirstName(){ }
return firstName;
}
19
Example
public double earnings()
public final class Boss extends
Employee1 { {
private double weeklySalary;
return weeklySalary;
public Boss( String first, String last,
}
double salary ){
super( first, last ); // call superclass
constructor
setWeeklySalary( salary ); // get String representation of
Boss's name
}
public String toString()
public void setWeeklySalary( double
salary ) { {
weeklySalary = ( salary > 0 ? salary : 0 ); return "Boss: " +
} super.toString();
}
} //
20
Example
public void setHours( double
public final class HourlyWorker
hoursWorked ){
extends Employee1 {
hours = ( hoursWorked >= 0 &&
private double wage; // wage per hour
hoursWorked < 168 ?
private double hours; // hours worked for
week hoursWorked : 0 );
public HourlyWorker( String first, }
String last, public double earnings() {
double wagePerHour, double hoursWorked
return wage * hours; }
){
super( first, last ); // call superclass public String toString(){
constructor return "Hourly worker: " +
setWage( wagePerHour ); super.toString();
setHours( hoursWorked );
}
}
}
public void setWage( double
wagePerHour )
{ wage = ( wagePerHour > 0 ?
wagePerHour : 0 );
} 21
Example boss.toString() + " earned $" +
public class Test { precision2.format( boss.earnings() ) +
"\n";
public static void main( String // Employee reference to an
args[] ){ HourlyWorker
Employee1 employee; // superclass employee = hourlyWorker;
reference--imposible to instantiate coz output += employee.toString() + "
abstract earned $" +
String output = ""; precision2.format(
Boss boss = new Boss( "John", "Smith", employee.earnings() ) + "\n" +
800.0 ); hourlyWorker.toString() + " earned $"
HourlyWorker hourlyWorker = new +
HourlyWorker( "Karen", "Price", 13.75, 40 ); precision2.format(
DecimalFormat precision2 = new hourlyWorker.earnings() ) + "\n";
DecimalFormat( "0.00" ); JOptionPane.showMessageDialog(
// Employee reference to a Boss null, output,
employee = boss; "Demonstrating Polymorphism",
output += employee.toString() + " earned $" + JOptionPane.INFORMATION_MESSA
GE );
precision2.format( employee.earnings() ) + "\n"
+ System.exit( 0 );
}
}
22
Exercise
Define three classes show how polymorhism achieved
Animal (name, location)..abstract
Dog (name, makesound())..concrete
Cat (name,makesound())..concrete
23
Exception Handling
Introduction
An Error "indicates serious problems that a reasonable application
should not try to catch."
An Exception "indicates conditions that a reasonable application
might want to catch.
An exception is an indication of a problem that occurs during a program’s
execution.
The name “exception” implies that the problem occurs infrequently—
if the “rule” is that a statement normally executes correctly, then the
“exception to the rule” is that a problem occurs.
Exception handling enables you to create
applications that can resolve (or handle) exceptions.
24
Basic idea:
Helps to write a robust and fault-tolerant programs
.
25
Exception Hierarchy
The Java exception hierarchy contains hundreds of
classes.
26
Cont…
java.lang.Object
java.lang.Throwable
ava.lang.Exception
java.lang.ClassNotFoundException
java.io.IOException
java.io.FileNotFoundException
java.lang.RuntimeException
java.lang.NullPointerException
ava.lang.IndexOutOfBoundsException
java.lang.ArrayIndexOutOfBoundsException
java.lang.Error
java.lang.VirtualMachineError
java.lang.OutOfMemoryError
27
Types of Exception
There are two types of exceptions:
checked exceptions
are checked at compile-time, It means
if a method is throwing a checked exception then it should handle the
exception using try-catch block or it should declare the exception
using throws keyword, otherwise the program will give a compilation
error.
Eg: SQLException,IOException,ClassNotFoundException
unchecked exceptions-(sub class of RuntimeException class).
are checked at runtime,It means
if your program is throwing an unchecked exception and even if you
didn’t handle/declare that exception, the program won’t give a
compilation error.
Most of the times these exception occurs due to the bad data provided
by user during the user-program interaction.
It is up to the programmer to judge the conditions in advance, that can
cause such exceptions and handle them appropriately.
Eg: ArithmeticException, NullPointerException,ArrayIndexOutOfBoundsException28
Examples: public static void main(String
args[]){
class Example { try{
public static void main(String int arr[] ={1,2,3,4,5};
args[]) { System.out.println(arr[10]);
}
int arr[] ={1,2,3,4,5}; catch(ArrayIndexOutOfBounds
System.out.println(arr[10]); Exception e){
}} System.out.println("The specified
index does not exist " +
What type of exception? "in array. Please correct the
error.");
}
}
29
How Exceptions are handled?
Using Try-Catch block
try{
statements
resource-acquisition statements
} // end try
catch ( AKindOfException exception1 )
{exception-handling statements
}
catch ( AnotherKindOfException exception2 )
{exception-handling statements
}
finally
{
statements
resource-release statements
}
30
Cont…
31
Cont…
1. Try
a try block, which encloses the code that might throwan
exception
and the code that should not execute if an exception occurs
the remaining code in the try block will be skipped if the
exception occurs.
A try block consists of the keyword try followed by a block of
code enclosed in curly braces ({})
2. throws clause
specifies the exceptions the method throws. This clause appears
after the method’s parameter list and before the method’s body.
It contains a comma-separated list of the exceptions that the
method will throw if a problem occurs
Eg-public static void main(String args[]) throws SQLException
32
Cont…
Throw vs Throws
Throws clause is used to declare an exception and thow keyword
is used to throw an exception explicitly.
Checked exception can only be propagated with throws.
Throws is followed by a Class but throw is followed by an instance
Throws is used with the method signature but throw is used inside a
method
You cannot throw multiple exceptions but possible to declare
multiple exceptions using throws
Without the throws clause in the signature the Java JVM compiler
does not know what to do with the exception.
The throws clause tells the compiler that this particular exception
would be handled by the calling method.
Eg:
ArithmeticException exp = new ArithmeticException(); throw exp;
Public void fun() throws IOException, ArithmeticException,
33
Cont…
3. A catch block/ exception handler )
catches /receives and handles an exception.
A catchblock begins with the keyword catch and is
followed by a parameter in parentheses (called the
exception parameter, )and a block of code enclosed in
curly braces.
At least one catchblock must imme-diately follow the
try block. Each catchblock specifies in parentheses an
exception-parameter that identifies the exception type
the handler can process
Eg- catch (SQLException ex ){}
34
Cont…
4. Finally block
Programs that obtain certain types of resources must
return them to the system explicitly,to avoid so-called
resource leaks .
In programming languages such as C and C++, the
most common kind of resource leak is a memory leak.
Java performs automatic garbage collec-tion of
memory no longer used by programs, thus avoiding
most memory leaks. However,
35
Example
import java.util.*;
import java.io.*;
public class ExceptionEg {
// demonstrates throwing an exception when a divide-by-zero occurs
public static int quotient( int numerator, int denominator )
{
return numerator / denominator; // possible division by zero
} // end method quotient
public static void main( String args[] )
{
Scanner scanner = new Scanner( System.in ); // scanner for input
boolean continueLoop = true; // determines if more input is needed
36
Cont…
do
{
try // read two numbers and calculate quotient
{
System.out.print( "Please enter an integer numerator: " );
int numerator = scanner.nextInt();
System.out.print( "Please enter an integer denominator: " );
int denominator = scanner.nextInt();
int result = quotient( numerator, denominator );
System.out.printf( "\nResult: %d / %d = %d\n" ,
numerator,denominator, result );
continueLoop = false; // input successful; end looping
} // end try 37
Cont…
catch ( InputMismatchException inputMismatchException )
{
System.err.printf( "\nException: %s\n",inputMismatchException );
scanner.nextLine(); // discard input so user can try again
System.out.println("You must enter integers. Please try again.\n" );
} // end catch
catch ( ArithmeticException arithmeticException )
{System.err.printf( "\nException: %s\n", arithmeticException );
System.out.println("Zero is an invalid denominator. Please try
again.\n" );
} // end catch
finally {System.out.println("finished");}
} while ( continueLoop );} } 38
Summary
Interfaces may specify but do not implement methods.
A class that implements the interface must implement all its
methods.
An interface, similar to an abstract class, cannot be instantiated
An interface has no constructors, only constants and method
declarations.
Classes implement interfaces using the keyword implements
Interface functions should be public and abstract.
Interface fields should be public ,static and final.
If you define a public interface with name myInterface the
java file should be named as myInterface.java (Similar to public
class definition rules).
An Interface can extends one or more interfaces.
You can define a reference of type interface but you should
assign to it an object instance of class type which implements
that interface.
Final or static classes cannot be overridden and final class
can’t be a super class because it can’t be modified/inherited
39