Professional Documents
Culture Documents
Interfaces
3 / 45
ANIMAL
picture
food
sleep()
roam()
makeNoise()
eat()
4 / 45
ANIMAL
picture
food
sleep()
roam()
makeNoise()
eat()
FELINE CANINE
roam() roam()
5 / 45
ANIMAL
picture
food
sleep()
roam()
makeNoise()
eat()
FELINE CANINE
roam() roam()
Problem
Need to add Pet behaviors to the pet animal
classes (Cat and Dog):
• play()
7 / 45
Option 1
Animal
Add concrete methods:
play() to Animal class
Feline Canine
Option 1
Animal
Add concrete methods:
play() to Animal class
Feline Canine
Option 1
Animal
Add concrete methods:
play() to Animal class
Feline Canine
Option 2
Animal
Add abstract methods: play()
to Animal class
Feline Canine
Option 2
Animal
Add abstract methods: play()
to Animal class
Feline Canine Provide empty body for it in
Lion and Wolf classes
Option 2
Animal
Add abstract methods: play()
to Animal class
Feline Canine Provide empty body for it in
Lion and Wolf classes
Option 3
Animal
Add concrete methods:
play() to Cat and Dog
classes
Feline Canine
What we need
Pet behaviors just in Pet classes (like Dog and Cat)
15 / 45
What we need
Pet behaviors just in Pet classes (like Dog and Cat)
What we need
Pet behaviors just in Pet classes (like Dog and Cat)
Multiple Inheritance?
Animal Pet
Feline Canine
Multiple Inheritance?
Animal Pet
Feline Canine
Multiple Inheritance?
Not allowed
A B
method() method()
C
21 / 45
A B
method() method()
Solution: Interfaces
Make Pet an interface and put all pet behaviors in it as abstract methods
Animal Pet
abstract play();
Feline Canine
Interfaces
Classlike construct
• contains only constants and abstract methods.
24 / 45
Interfaces
Classlike construct
• contains only constants and abstract methods.
• cannot contain variables or concrete methods.
25 / 45
Interfaces
Classlike construct
• contains only constants and abstract methods.
• cannot contain variables or concrete methods.
Declaration:
public interface <InterfaceName> {
// constant declarations;
// method signatures;
}
26 / 45
Interface Pet
public interface Pet {
public void play();
}
27 / 45
Interface Characteristics
Interfaces are defined in their own file
30 / 45
Interface Characteristics
Interfaces are defined in their own file
Interface Characteristics
Interfaces are defined in their own file
Interface Characteristics
Interfaces are defined in their own file
Example
public interface Interface1 {
int aNumber = 0;
Example
public interface Interface1 {
int aNumber = 0;
Same as:
public interface Interface1 {
public static final int aNumber = 0;
Interface Characteristics
A class can implement any number of interfaces
}
36 / 45
Interface Characteristics
A class can implement any number of interfaces
Interface Characteristics
A class can implement any number of interfaces
Robot
Animal
Pet
abstract play();
Feline Canine
RoboDog Roomba
Next Lecture
More on interfaces