1.1接口中的方法都被自动设置为public,接口中的域将被自动设置为public static final.
1.2对象克隆
当拷贝一个变量时,原始变量与拷贝变量引用同一个对象(改变一个变量所引用的对象,会对另一个变量产生影响)
Employee original = new Employee("John Public",50000);
Employee copy = original;
copy.raiseSalary(10);//original也会改变
//浅拷贝:将各个域进行对应的拷贝
Employee original = new Employee("John Public",50000);
Employee copy = original.clone();
copy.raiseSalary(10);//如果对象中包含了子对象的引用,拷贝结果会使得两个域引用同一个对象。
即使clone的默认实现(浅拷贝)能满足要求,也应实现Cloneable接口,将clone重定义为public
class Employee implements Cloneable{
public Employee clone() throws CloneNotSupportedException{
return (Employee)super.clone();
}
...
}
//深拷贝
class Employee implements Cloneable{
public Employee clone() throws CloneNotSupportedException{
Employee cloned = (Employee)super.clone();
cloned.hireDay = (Date)hireDay.clone();//子对象
return cloned;
}
...
}
2内部类
2.1内部类既可以访问自身的数据域,也可以访问创建他的外部类的对象的数据域。
2.2只有内部类可以是私有类。
2.3内部类是一种编译器现象,与虚拟机无关。
2.4局部内部类
局部类不能用public或private访问说明符进行声明,它的作用域被限定在声明这个局部类的块中。
public void start()
{
class TimePrinter implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
Date now = new Date();
System.out.println("At the tone, the time is " + now);
if (beep) Toolkit.getDefaultToolkit().beep();
}
}
ActionListener listener = new TimePrinter();
Timer t = new Timer(interval, listener);
t.start();
}
与其他内部类相比,局部类不仅能访问包含他们的外部类,还可以访问声明为final的局部变量。
2.5匿名内部类
只创建局部内部类的一个对象;匿名类没有类名,因此不能有构造器。
匿名内部类只能实现一个接口。
public void start()
{
ActionListener listener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
Date now = new Date();
System.out.println("At the tone, the time is " + now);
if (beep) Toolkit.getDefaultToolkit().beep();
}
};
Timer t = new Timer(interval, listener);
t.start();
}
2.6静态内部类
在内部类不需要访问外围类对象的时候应该使用静态内部类(声明为static)
在静态方法中构造的内部类必须使用静态内部类。
声明在接口中的内部类自动成为static和public.
class ArrayAlg
{
public static class Pair
{
public Pair(double f, double s)
{
first = f;
second = s;
}
...
}
public static Pair minmax(double[] values)
{
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
for (double v : values)
{
if (min > v) min = v;
if (max < v) max = v;
}
return new Pair(min, max);
}
}
2.7代理
代理类在程序运行过程中创建,一旦被创建,就变成常规类。
代理类都一定是public和final;
所有代理类都扩展于Proxy类,一个代理类只有一个实例域:调用处理器。