接口技术用来描述类具有什么功能,而并不给出每个功能的具体实现。
一个类可以实现一个或者多个接口,并在需要借口的地方,随时使用实现了相应接口的对象。
为了让类实现某个接口,通常需要:
package com.xujin; public class Main{ public static void main(String...args){ Employee e = new Employee("Lily", 1000); System.out.print(e.compareTo(new Employee("Bob", 2000)));//1 } } class Employee implements Comparable<Employee>{ public Employee(String name, double salary){ this.name = name; this.salary = salary; } public int compareTo(Employee other){ if(salary > other.salary) return -1; if(salary < other.salary) return 1; return 0; } //定义变量 private double salary; private String name; }
Comparable x = new Employee("Jim", 4000);//这里x是Employee类型的 System.out.println(x.getClass().getName());//com.xujin.Employee这样,创建的x是Employee类型的。
class Employee implements Cloneable, Comparable{ ...... }
package com.xujin; public class Main{ public static void main(String...args) throws CloneNotSupportedException{ Employee a = new Employee("Lily", 1000); Employee staff = a;//a与staff同时引用同一个对象 a.setName("Bob"); System.out.println(a);//com.xujin.Employee[name = Bob, salary = 1000.0] System.out.println(staff); //com.xujin.Employee[name = Bob, salary = 1000.0] Employee copy = a.clone(); a.setName("Jim"); a.setSalary(2000); System.out.println(a);//com.xujin.Employee[name = Jim, salary = 2000.0] System.out.println(copy);//com.xujin.Employee[name = Bob, salary = 1000.0] } } class Employee implements Cloneable{ public Employee(String name, double salary){ this.name = name; this.salary = salary; } public String getName(){ return this.name; } public double getSalary(){ return this.salary; } public void setName(String name){ this.name = name; } public void setSalary(double salary){ this.salary = salary; } public String toString(){ return getClass().getName() + "[name = " + name + ", salary = " + salary + "]"; } public Employee clone() throws CloneNotSupportedException{ return (Employee)super.clone(); } //定义变量 private double salary; private String name; }
ackage com.xujin; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Date; import javax.swing.JOptionPane; import javax.swing.Timer; public class Main{ public static void main(String...args){ ActionListener listener = new TimePrinter(); Timer t = new Timer(1000, listener); t.start(); JOptionPane.showMessageDialog(null, "Quit?"); System.exit(0); } } class TimePrinter implements ActionListener{ public void actionPerformed(ActionEvent event){ Date now = new Date(); System.out.println("At the tone,the time is " + now); Toolkit.getDefaultToolkit().beep(); } }