A5: Multiple Interfaces

CPSC 210

🚊             🚘             🚲            🚶‍♀️             🚕

🏋️‍♀️💦

Learning Goals

  • Using multiple interfaces
    • to state that some code uses an object from the particular perspective of one of those interfaces
    • to allow you to declare multiple super types for a class

I want to make any barking animal bark and I don't care if it's a dog or not!

for (Barking barker : barkers) {
  barker.bark();
}

// "WOOOFF"
// "WUUUUUFFF"
// "WAAAAAFFF"
// "GRAAAA"
// "WOOOFF"

Why Interfaces?

Multiple Interfaces

void walk()

Dog

void fetchStick()

Fox

void fetchChicken()

Walking

void walk()

<<interface>>

Barking

void bark()

<<interface>>

Multiple Interfaces (2)

void makeThingBark(Barking barker) {
  barker.bark();
}
void makeThingWalk(Walking walker) {
  walker.walk();
}
Barking barkingWolf = new Wolf();
Walking walkingWolf = new Wolf();
Wolf explicitWolf = new Wolf();

makeThingBark(barkingWolf); // ???
makeThingWalk(barkingWolf); // ???
makeThingBark(walkingWolf); // ???
makeThingWalk(walkingWolf); // ???
makeThingBark(explicitWolf); // ???
makeThingWalk(explicitWolf); // ???

Lecture Ticket Review

Bakery

void serveCookie()

<<interface>>

CoffeeShop

void serveCookie()
void serveCoffee()

<<interface>>

Kiosk

what method/s
must be implemented
in this class?

Lecture Ticket Review (2)

Bakery

void serveCookie()

<<interface>>

CoffeeShop

void serveCookie()
void serveCoffee()

<<interface>>

Kiosk

what method/s
must be implemented
in this class?

Lecture Ticket Review (3)

Bakery

void serveCookie()

<<interface>>

CoffeeShop

void serveCookie()
void serveCoffee()

<<interface>>

Kiosk

what method/s
must be implemented
in this class?

Lecture Lab: Learners

Lecture Lab

Which would compile?

Learner student = new Student();
student.getCourses();
Student student = new Student();
student.getCourses();
HasCourses somebodyWithCourses = new Student();
somebodyWithCourses.getCourses();

B

A

C

Lecture Lab (5)

University uni = new University();
Learner learner = new Student();
uni.teach(learner);
University uni = new University();
HasCourses somebodyWithCourses = new Student();
uni.teach(somebodyWithCourses);
University uni = new University();
Student student = new Student();
uni.teach(student);

A

B

C

public class University {
  public void teach(
    Learner learner) {
    // ...
  }
  public void register(
    HasCourses somebodyWithCourses) {
    // ...
  }
}

Which would compile?

University uni = new University();
Learner learner = new Student();
uni.register(learner);

D

University uni = new University();
Student student = new Student();
uni.register(student);

E

University uni = new University();
HasCourses somebodyWithCourses 
    = new Student();
uni.register(somebodyWithCourses);

F

A5: Multiple Interfaces

The End - Thank You!

CPSC210 - A5 Multiple Interfaces

By meghanallen

CPSC210 - A5 Multiple Interfaces

  • 143