An interface is similar to an abstract class in that a class that implements an interface is REQUIRED to define certain methods.
An interface must only contain constants and abstract methods, no variables.
GUI Example: DogYearsListen.java
// The ActionListener interface contains only one abstract
// method called actionPerformed().
// Because the class ConvertBtnListener implements the
// ActionListener interface, it is required to define the
// actionPerformed() method.
class ConvertBtnListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// Assume that the GeometricObject1, Circle4 and
// Rectangle1 classes are defined already:
public class PolymorphismDemo {
public static void main(String[] args) {
// Display Circle and rectangle properties
displayObject(new Circle4(1, "red", false));
displayObject(new Rectangle1(1, 1, "black", true));
}
/** Method to display geometric object properties */
// (POLYMORPHISM BEING EMPLOYED HERE:)
public static void displayObject(GeometricObject1 object) {
System.out.println("Created on " + object.getDateCreated() +
". Color is " + object.getColor());
}
}
public class DynamicBindingDemo {
public static void main(String[] args) {
m(new GraduateStudent());
m(new Student());
m(new Person());
m(new Object());
}
// (POLYMORPHISM BEING EMPLOYED HERE:)
public static void m(Object x) {
System.out.println(x.toString());
}
}
class GraduateStudent extends Student {
}
class Student extends Person {
public String toString() {
return "Student";
}
}
class Person extends Object {
public String toString() {
return "Person";
}
}
public interface Relatable
{
public abstract boolean equals(GradedActivity g);
public abstract boolean isGreater(GradedActivity g);
public abstract boolean isLess(GradedActivity g);
}
Polymorphism can help to reduce the number of listeners that are required for
GUI components.