介面解決 Java 單繼承限制,一個類別可實作多個介面。本範例展示兩個介面 Sing、Print,以及 Student (單實作) 與 Teacher (多實作) 的設計。
public interface Sing {
String EYE_COLOR = "black"; // public static final
void sleep();
void sing();
}
public interface Print {
String SEX = "woman";
void print();
void eat();
}
public class Student implements Sing {
private String name;
public Student(String name) { this.name = name; }
public String getName() { return name; }
@Override public void sleep() { System.out.println("Student is sleeping"); }
@Override public void sing() { System.out.println("Student is singsong"); }
public void all() { System.out.println("這位名叫 " + name + " 的 Student 是一位喜歡唱歌的人"); }
}
public class Teacher implements Sing, Print {
private int age;
public Teacher(int age) { this.age = age; }
public int getAge() { return age; }
@Override public void print() { System.out.println("Teacher is print"); }
@Override public void eat() { System.out.println("Teacher is eating"); }
@Override public void sleep() { System.out.println("Teacher is sleeping"); }
@Override public void sing() { System.out.println("Teacher is singsong"); }
public void info() { System.out.println("這位 " + age + " 歲的教師既會唱歌又會畫畫"); }
}
public class Test {
public static void main(String[] args) {
Student s1 = new Student("LiQing");
s1.sleep(); s1.sing(); s1.all();
Sing t1 = new Teacher(25); // 向上轉型為 Sing
t1.sing(); t1.sleep();
Print p1 = (Print) t1; // 強制轉型為 Print
p1.print(); p1.eat();
Teacher t2 = (Teacher) t1; // 還原具體類別
t2.info();
}
}
Student is sleeping
Student is singsong
這位名叫 LiQing 的 Student 是一位喜歡唱歌的人
Teacher is singsong
Teacher is sleeping
Teacher is print
Teacher is eating
這位 25 歲的教師既會唱歌又會畫畫
public static final,方法隱含 public abstract。