6.1 接口
接口不是类,而是对类的一组需求描述。
接口中所有方法自动属于public 。因此在声明时,不必提供关键字public
在接口中,可以定义常量。
浮点数比较大小时,可能因舍入产生 错误。
在接口中,
似乎能定义静态方法?
接口中的常量被自动设为public static final。 此时的静态方法就没有意义。
6.2 对象克隆
Object 类中的clone() 是 浅拷贝
Cloneable接口
所有数组都有一个clone()方法
6.4 内部类
内部类对象有一个隐式引用,它引用了实例化该内部对象的外围类对象。
内部类-局部内部类- 匿名内部类-静态内部类(只为隐藏,不需引用外部类对象)
public void start(int interval, final boolean beep)//<span style="font-family: Arial, Helvetica, sans-serif;">final</span>
<span style="white-space:pre"> </span>class TimePrinter implements ActionListener
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>public void actionPerformed(ActionEvent event)
<span style="white-space:pre"> </span>{ <span style="white-space:pre"> </span>Date now = new Date();
<span style="white-space:pre"> </span>System.out.println("At the tone, the time is " + now);
<span style="white-space:pre"> </span>if (beep) Toolkit.getDefaultToolkit().beep();
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>ActionListener listener = new TimePrinter();
<span style="white-space:pre"> </span>Timer t = new Timer(interval, listener);
<span style="white-space:pre"> </span>t.start();
}
class TalkingClock$1TimePrinter
{
<span style="white-space:pre"> </span>TalkingClock$1TimePrinter(TalkingClock, boolean);
<span style="white-space:pre"> </span>public void actionPerformed(java.awt.event.ActionEvent);
<span style="white-space:pre"> </span>final boolean val$beep;
<span style="white-space:pre"> </span>final TalkingClock this$0;
}
ArrayList<String> friends = new ArrayList<>();
favorites.add("Harry");
favorites.add("Tony");
invite(friends);
invite(new ArrayList<String>() {{ add("Harry"); add("Tony"); }})
获得Object匿名子类的外部类 。可得到静态方法所在类
new Object(){}.getClass().getEnclosingClass() // gets class of static method
声明在
接口中的内部类自动成为static和public类
6.5 代理
在运行时创建一个实现了一组给定接口的新类
class TraceHandler implements InvocationHandler
{
<span style="white-space:pre"> </span>private Object target;
<span style="white-space:pre"> </span>public TraceHandler(Object t)
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>target = t;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public Object invoke(Object proxy, Method m, Object[] args)
<span style="white-space:pre"> </span>throws Throwable
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>// print method name and parameters
<span style="white-space:pre"> </span>// invoke actual method
<span style="white-space:pre"> </span>return m.invoke(target, args);
<span style="white-space:pre"> </span>}
}
Object value = . . .;
// construct wrapper
InvocationHandler handler = new TraceHandler(value);
// construct proxy for one or more interfaces
Class[] interfaces = new Class[] { Comparable.class};
Object proxy = Proxy.newProxyInstance(null, interfaces, handler);
代理类覆盖了Object类中的方法toString,equals和hashCode,如同代理方法一样,这些方法仅仅调用了调用处理器的invoke