0% found this document useful (0 votes)
13 views

Chapter Five

Polymorphism allows performing a single action in different ways. There are two types of binding: early/static binding and late/dynamic binding. Polymorphism is commonly used with inheritance, where a superclass reference can refer to subclass objects. Abstract classes cannot be instantiated but can contain abstract and concrete methods, while interfaces only contain abstract methods and constants.

Uploaded by

Biniam Teferi
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)
13 views

Chapter Five

Polymorphism allows performing a single action in different ways. There are two types of binding: early/static binding and late/dynamic binding. Polymorphism is commonly used with inheritance, where a superclass reference can refer to subclass objects. Abstract classes cannot be instantiated but can contain abstract and concrete methods, while interfaces only contain abstract methods and constants.

Uploaded by

Biniam Teferi
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/ 31

Chapter Five

POLYMORPHISM
AND
INTERFACES
3/1/2020
Polymorphism
2

 Polymorphism means to assign multiple meaning to the same


method name
 Polymorphism is one of the OOPs feature that allows us to
perform a single action in different ways.
 There are two types of binding
1. Early/Static Binding/Overloading
 Binding that takes place during compilation time

2. Late/dynamic Binding/Overriding
 Binding that takes place at a runtime

• All instance Methods except static, private, final have dynamic


binding

3/1/2020
Overloading

class Test {
public static void main(String args[]) {
myPrint(5);
myPrint(5.0);
}
static void myPrint(int i) {
System.out.println("int i = " + i);
}
static void myPrint(double d) { // same name, different parameters
System.out.println("double d = " + d);
}
}
int i = 5
double d = 5.0

3
Overriding
 This is called
class Animal {
public static void main(String args[]) { overriding a method
Animal animal = new Animal();
 Method print in Dog
Dog dog = new Dog();
animal.print(); overrides method
dog.print(); print in Animal
}
void print() {  A subclass variable
System.out.println("Superclass Animal"); can shadow a
} superclass variable,
}
but a subclass
public class Dog extends Animal {
void print() {
method can
System.out.println("Subclass Dog"); override a
} Superclass Animal superclass method
} Subclass Dog

4
Example
5

Public class food


{
Public void eat(){ Public class Apples
Sytem.out.println(“The food is great”); {
}} public static void main (String [] args){
Public class Bread extends food{
Public void eat(){ food F0=new food();
Sytem.out.println(“The bread is great”); food F1=new Bread();
}} food F2=new fruit();
Public class fruit extends food{ F0.eat();
Public void eat(){ F1.eat();
Sytem.out.println(“The fruit is great”); F2.eat();
} The food is great
} The bread is great
}
The fruit is great
}

3/1/2020
6

 A very common usage of polymorphism: If


classes C1, C2, ...., Cn are all derived from C,
define an array A of elements of C.
The entries A[i] can then refer to objects of
classes C1, ...., Cn.
C

C1 C2 C3

3/1/2020
Example
7

Public class food


{
Public void eat(){ Public class Apples
Sytem.out.println(“The food is great”); {
}} public static void main (String [] args){
Public class Bread extends food{
Public void eat(){ food [] F=new food[3];
System.out.println(“The bread is F[0]=new food();
great”); F[1]=new Bread();
}} F[2]=new fruit();
Public class fruit extends food{
Public void eat(){ for(int i=0;i<3;i++){
System.out.println(“The fruit is great”); F[i].eat();
} } The food is great
} The bread is great
} } The fruit is great

3/1/2020
Abstract class
8

 Abstract class is a class from which you cannot create an


object
 They have a key word abstract

Syntax: public abstract ClassName{


//body
}
• It can have abstract methods(methods without body)
as well as concrete methods (regular methods with
body).
 An abstract class often contains abstract methods,
though it doesn’t have to

3/1/2020
Example
9

public abstract class Vehicle


{
String name;

public String getName()


{ return name; } \\ method body

abstract public void move();


\\ no body!
}

3/1/2020
Abstract Method
10

 Methods which are declared using abstract Keyword


 They do have no body statement, no carry brace

Syntax: public abstract returntype MethodName();

 If a subclass of an abstract superclass does not


implement all the abstract methods, the subclass
must be defined abstract
 The non-abstract child of an abstract class must
override the abstract methods of the parent
 An abstract method cannot be contained in a
nonabstract class

3/1/2020
Example
11

public abstract class Animal public class Cow extends Animal{


{ public void sound(){
Private String name; System.out.println(“Moo”);
public abstract void sound(); } }
public String getname(){ public class UseAnimal
return name; {
} Public static void main(String [] args)
public void setname(String n){ Animal MyDog=new Dog();
name=n; Animal mycow=new Cow();
}} MyDog.setname(“Jak”);
public class Dog extends Animal MyCow.setname(“Elsie”)
{
public void sound(){ System.out.println(MyDog.getname+”Says”);
System.out.println(“Woof”); MyDog.sound();
System.out.println(MyCow.getname+”Says”);
}
MyCow.sound();
} }}

3/1/2020
Interface
12

 A Java interface is a collection of constants and


abstract methods
 Specifies the headings for methods that must be
defined in any class that implements the interface
 Contains all methods headings, no instance variable,
no complete definitions of methods
Syntax: public interface interface_Name{
public Constant_declaration;
public Method headings;
}

3/1/2020
Interface: Syntax
13
interface is a reserved word

public interface Doable


{
public static final String NAME;

public void doThis();


public int doThat();
public void doThis2 (float value, char ch);
public boolean doTheOther (int num);
}

A semicolon immediately
follows each method header
No method in an
interface has a definition (body)
Conti…
14

 An interface does not define any constructor for a class


 Method within an interface must be abstract and public
such that this keyword may be omitted.
 Fields within interface should also be public and final.
 To implement the interface
1. Class must include the phrase
implement Interface_Name
2. Class must have to define all methods declared within
interface

3/1/2020
Example
15

interface Shape{
String baseClass=“Shape”;
public void draw();
}
public class Circle implements Shape{
public void draw(){
Syste.out.println(“Drawing Circle Here”);
}}
public class Interfacedemo{
public static void main(String [] args){
Shape CircleShape=new Circle();
CircleShape.draw();
}
}

3/1/2020
Abstract class Versus Interface
16

 Their similarity is that you Can't create an object


form both
 Differences of Abstract class and Interface
Interface Abstract Class

 Contain only abstract  Contain both abstract and


method Concrete Methods
 Class can implement  Class can inherit only from one
many interface abstract class
 Contain only Constant  Contain Constant and other
Variable variable also
 Abstract class cannot inherit
another abstract

3/1/2020
Chapter Six
17

EXCEPTION
HANDLING

3/1/2020
Exception Handling
18

 An Exception is an object that signals the


occurrence of an usual event during the execution
of a program.
 A process of creating this object and handing it to
the runtime system is called throwing exception.
 An exception is an event that occurs during the
execution of a program that disrupts the normal
flow of instructions.

 The code that deals with the exception is said to


be Exception Handling.

3/1/2020
Types Of Errors
19

 Three types of Errors in java:


1. Syntax errors arise because the rules of the
language have not been followed. They are detected
by the compiler
2. Runtime errors occur while the program is
running if the environment detects an operation that
is impossible to carry out
3. Logic errors occur when a program doesn't
perform the way it was intended to.

3/1/2020
Types of Exceptions
20
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
AWTError

Several more classes


Example
21

public class Division


{
Public static void main(String [] args){
Scanner input=new Scanner(System.in)
int n;
int d;
int r;

System.out.println(“Enter a Numerator”);
n=input.nextInt();
System.out.println(“Enter a Denominator”);
d=input.nextInt();
r=n/d;
System.out.println(n+”/”+d+”=”+r);
}
}

3/1/2020
Try…Catch Mechanism
22

 Syntax:
try{
//Statement that generate an exception
}
catch(Exception someException)
{
//action to be taken if Exception occurs
}

3/1/2020
Example
23

public class Division try{


{ r=n/d;
Public static void main(String [] args){
Scanner input=new Scanner(System.in)
System.out.println(n+”/”+d+”=”+r);
int n; }
int d; Catch(ArthmeticException E){
int r; System.out.println(“Attempts to
System.out.println(“Enter a Numerator”); divide By Zero”);
n=input.nextInt();
System.out.println(“Enter a }
Denominator”);
d=input.nextInt();
}

}
}

3/1/2020
Notes
24

 Any ArithmeticException generated within the try


block in the program should be caught by the catch
block
 You can use getMessage() method
catch (ArithmeticException e){
System.out.println(e.getMessage());
}
 You can place as many statement as you need within
a try block and you can catch as many Exception as
you want.

3/1/2020
Example
25

public class Division


{ Catch(ArthmeticException E){
Public static void main(String [] args){
Scanner input=new Scanner(System.in);
System.out.println(“Attempts to
int n; divide By Zero”); }
int d; catch(InputMismatchException E){
int r;
try{ Sytem.out.println(“Wrong data type ”);
System.out.println(“Enter a }
Numerator”);
n=input.nextInt();
System.out.println(“Enter a
Denominator”);
d=input.nextInt(); }}
r=n/d;
System.out.println(n+”/”+d+”=”+r);
}

3/1/2020
Note
26

 Sometimes when an exception is thrown you want


your code to simply repeat some code. So that the
user can get things on a second subsequent try called
Exceptions Controlled Loops.

3/1/2020
Example
27

Public class Demo catch(InputMismatchException E)


{ {
Public static void main(String [] args){ System.out.println(“Not Correctly
Scanner input=new Scanner(System.in); entered Whole Number. Try
int number; again”);
boolean done=false;
}
While(!done){
Sytem.out.println(“You
try{ enterd”+number); } }
System.out.println(“Enter
A whole number”);
number=input.nextInt();
done=true;
}
}

3/1/2020
Finally Block
28

 When you have actions you must perform at the end of


try catch sequence you can use finally block
 Syntax:
try{
}
catch(Exception e){
}
finally{
//action that occur whether catch block execute or
not
}

3/1/2020
Example Write output
29
public class Division { catch(Exception E){
int a=5; System.out.println("Division Error");
int b=0; }
public void Java(){
finally{
System.out.println(“Finally Block");
}
System.out.println(“Finally Block”);
public void Division() }
{ }}
System.out.println(a/b); Public class Test{
}} public static void main(String[] args)
class A extends Division{ {
public void Division(){ A b=new A();
try{ super.b=5; System.out.println("Your Output Must
super.Division(); Be Correct!");
System.out.println(a*b); b.Division();
} }}

3/1/2020
Last Quiz
30
public class AA { public class Quiz2 {
public int Max(int a,int b){ public static void main(String[] args)
if(a>b){ {
return a; } CC c= new CC();
else { System.out.println("I Miss You");
return b; } System.out.println(c.Max(10, 15));
} } }}
Public class BB extends AA
{ public int Max(int a,int b){
System.out.println("I Miss You");
return super.Max(a+7, b);
}}
Public class CC extends BB
{ public int Max(int a,int b){
return (super.Max(a, b))+10;
}}

3/1/2020
Thank you!

You might also like