Object-Oriented Programming
Interfaces in Java
Important OO Concepts
encapsulation
"P.I.E“
triangle
abstraction
inheritance polymorphism
2
Why care about Interface?
Supported via the
use of Interface
3
What is Interface?
• In Java, interface is a special type of class which:
– Define a set of method prototypes
– Does not provide the implementation for the
prototypes
– Can also define final constants
public interface Animal {
public abstract void eat();
public abstract void travel();
}
4
Creating Interface
• To define an interface: Use keyword interface instead of
public interface Animal { class
public abstract void eat(); the methods are ALL abstract
public abstract void travel();
}
keyword implements
• To implement an interface:
public class Mammal implements Animal {
public void eat(){
[Link](“Mammal eats meat”);
}
implements ALL Animal
methods
public void eat(){
[Link](“Mammal travels around”);
}
normal overriding methods
public int noOfLegs(){
return 0;
} 5
}
Multiple Inheritance with Interface
• Classes from difference inheritance trees can
implement the same interface
6
Multiple Inheritance with Interface
• A class can implement multiple interfaces
7
Extends vs. Implements Keyword
• A class
– Can “extend” only one class, i.e. ONE superclass
– Can “implement” MULTIPLE interfaces
8
Implement Multiple Interfaces
ActionCharacter "interface" "interface" "interface"
CanFight CanSwim CanFly
SuperHero
• Class “SuperHero”
– Extends class “ActionCharacter”
– Implements three interfaces “CanFight”,
“CanSwim”, “CanFly”
9
Implement Multiple Interfaces
interface CanFight {
void fight();
}
interface CanSwim {
void swim();
}
interface CanFly {
void fly();
}
class ActionCharacter {
public void fight() {
[Link](“Fight well”);
}
} class SuperHero extends ActionCharacter implements CanFight,
CanSwim, CanFly {
public void swim() {
[Link](“Swim well”);
}
public void fly() {
[Link](“Fly well”);
}
}
10
Extend an Interface with Inheritance
interface Monster {
void menace();
}
interface Lethal {
void kill();
}
interface Vampire extends Monster, Lethal {
void drinkBlood();
}
class VeryBadVampire implements Vampire {
public void menace() {
[Link](“Vampire menaces people”);
}
public void kill() {
[Link](“Vampire kills people”);
}
public void drinkBlood() {
[Link](“Vampire drinks blood”);
}
}
11
12