Slides For 2-25-15
Slides For 2-25-15
Slides For 2-25-15
2015/02/25
Learning Objectives
Demonstrate an understanding of interfaces
by using real-world examples.
Give three reasons to use interfaces.
Understand has-a relationships.
Agenda
Interface: A definition
An interface is a variable type that consists of a
set of method declarations, which any
implementing classes promise to define.
Interface: A definition
An interface is a variable type that consists of a
set of method declarations, which any
implementing classes promise to define.
What do shapes promise to implement?
So why do we care?
When implementation might differ, but
behavior is constant
When the specific type of an object is
unknown
When we want to ensure certain behavior
Different implementations
public interface D oor {
//W hat goes here?
}
public class SlidingD oor im plem ents D oor {
//W hat goes here?
}
public class RegularD oor im plem ents D oor {
//W hat goes here?
}
Different implementations
public interface D oor { public void open(); }
public class SlidingD oor im plem ents D oor {
public void open() { System .out.println("Sliding..."); }
}
public class RegularD oor im plem ents D oor {
public void open() {
System .out.println("Turning on hinges...");
}
}
Different implementations
A real example in Java:
ArrayList and LinkedList both implement
the interface List
Ensuring behavior
Implementing Com parable guarantees that
any two objects of that type can be
compared.
It contains one method: com pareTo()
Multiple interfaces
What if we wanted to make Circles
comparable?
We can!
public class Circle im plem ents Shape,
Com parable {...}