吧Github代码链接: https://github.com/deyou123/corejava.git
第六章 接口、lambda表达式和内部类
6.1 接口
6.1.1 接口概念
- 接口不是类,而是对类的一组需求描述。
- ex: Comparable接口
public interface Comparable{
int compareTo(Object other);
}
public interface Comparable<T>{
int compareTo(T other);
}
不带参数,compareTo是Object类型
-
接口中所有方法自动地属于public,不必提供关键字public
-
接口中可能包含多个方法。
-
接口中还可以定义常量。
-
接口不饿能提供哪些功能:
- 接口中绝对不能含有实例域
- Java SE8 之前不能在接口中实现方法;现在已经可以在接口中提供简单方法了;这些方法不能引用实例域。
-
可以将接口看成是没有实例域的抽象类。
-
为了让类实现一个接口,需要两个步骤
1、将类声明为实现给定的接口
2、对接口中的所有方法进行定义。 -
implements:
class Employee implements Comparable
public int compareTo(Object otherObj){
Employee other = (Employee)otherObj;
return Double.compare(salary,otherObj.salary);
}
- 在实现接口时,必须把方法声明为public;否则编译器会提出访问权限的警告信息。
6.1.2 接口的特性
- 接口不是类,不能new实例
- 可以生命接口变量;必须引用实现了接口的类对象
- 可以使用instanceof检查一个对象是否实现了某个特定的接口
if(obj instanceof Comparable){…} - 接口可以被扩展;允许存在多条从具有较高通用性的接口到较高专用性接口的链。
public interface Moveable{
void move(double x, double y);
}
public interface Powered extends Moveable
{
double milesPerGallon();
}
- 接口可以包含常量;接口中的域都将被自动设为 public static final
public interface Powered extends Moveable{
double milesPerGallon();
double SPEED_LIMIT = 95;
}
- Cloneable接口,clone方法可以创建类对象的一个拷贝。
6.1.3 接口与抽象类
- 每个类只能扩展于一个类
6.1.4 静态方法
- Java SE8 中,允许存在接口中增加静态方法;只是有违将接口作为抽象规范的初衷。
- 通常的做法是将静态方法放在伴随类中;ex成对出现的接口和使用工具类,Collection/Collections 或 Path/Paths
- ex
public interface Path
{
public static Path get(String first,String... more){
return FileSystems.getDefault().getPath(first, more);
}
}
6.1.5 默认方法
- 可以为接口方法提供一个默认实现;default修饰符
- 实现接口的程序员只需要为他们真正关系的事件覆盖相应的监听器。
6.1.6 默认方法冲突
- 接口中一个默认方法,父类或者另一个接口中定义了同样的方法
1、父类优先,其他默认方法会被忽略。
2、接口冲突,必须覆盖这个方法来解决冲突。
6.2 接口示例
6.2.1 接口与回调
回调:是一种常见的设计模式;可以指出某个特定事件发生时应该采取的动作;
ex:可以指出按下鼠标或者选择某个菜单项时应该采取什么行动。
public class TimerTest
{
public static void main(String[] args)
{
ActionListener listener = new TimePrinter();
// construct a timer that calls the listener
// once every 10 seconds
Timer t = new Timer(1000, listener);
t.start();
JOptionPane.showMessageDialog(null, "Quit program?");
System.exit(0);
}
}
class TimePrinter implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
System.out.println("At the tone, the time is " + new Date());