CHAP5-polymorph & Exceptions
CHAP5-polymorph & Exceptions
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.
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
15
(cont’d)
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 );
23
Exception Handling
Introduction
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.
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