![]() |
Jupyter at Bryn Mawr College |
|
|
Public notebooks: /services/public/dblank / CS206 Data Structures / 2016-Spring / Notebooks |
Interfaces are used to define a set of methods that a class must have in order to be a valid type of that class.
interface
extends
that interfaceFirst we define an interface:
interface Human {
public abstract double age();
}
What can we do with it?
Human is sorta like a type/class... we spell it with a capital letter....
new Human()
No, you can create an instance of an interface. But you can create a class that implements it:
class Student implements Human {
}
...but only if you satisfy the requirements of the interface:
class Student implements Human {
public double age() {
return 19.0;
}
}
Now, you can use the class as you would normally:
Student student = new Student();
student.age();
In addition, you can "cast" a class as an interface. If you do that, you can only use methods that exist in Human:
Human human = student;
You can also cast it explicitly like: ((Human)student)
human.age()
class Student implements Human {
public double age() {
return 19.0;
}
public boolean in_cs206() {
return true;
}
}
Student student = new Student();
student.in_cs206();
class Teacher implements Human {
public double age() {
return 52.0;
}
public boolean has_tenure() {
return true;
}
}
Teacher teacher = new Teacher();
teacher.age()
ArrayList<Human> alist = new ArrayList<Human>();
alist.add(teacher);
alist.add(student);
for (Human human: alist) {
printf("Age: %s\n", human.age());
}
Human human = teacher;
teacher.has_tenure()
See page 6 of your textbook for more information.