1.当拷贝一个变量时,原始变量与拷贝变量引用同一个对象,改变一个变量所引用的对象将会对另一个变量产生影响。
a a1 = new a(); a a2 = a1; a2.up(10);//a1也会改变
a a1 = new a(); a a2 = a1.clone(); a2.up(10);//a1不会改变了
4.默认的克隆操作是浅拷贝,它并没有克隆包含在对象中的内部对象。
5.如果一个对象需要克隆,而没有实现Cloneable接口,就会产生一个以检验异常。
6.即便clone的默认实现即浅拷贝能够满足需求,也应该实现Cloneable接口,将clone重定义为public,并调用super.clone()。
7.只要在clone中没有实现Cloneable接口的对象,Object类的clone方法就会抛出一个CloneNotSupportException异常。
实例代码
测试类
public class test {
public static void main(String[] args)
{
try
{
Employee exp = new Employee("w1",1000);
exp.setHireDay(2014, 4, 2);
Employee copy = exp.clone();
copy.raiseSalary(50);
copy.setHireDay(2014, 3, 2);
System.out.println("exp =" + exp);
System.out.println("copy =" + copy);
}
catch(CloneNotSupportedException e)
{
e.printStackTrace();
}
}
}
import java.util.*;
public class Employee implements Cloneable {
private String name;
private double salary;
private Date hireDay;
public Employee(String n,double s)
{
name = n;
salary = s;
hireDay = new Date();
}
public Employee clone() throws CloneNotSupportedException
{
Employee cloned = (Employee) super.clone();
cloned.hireDay = (Date)hireDay.clone();
return cloned;
}
public void setHireDay(int year,int month,int day)
{
Date newHireDay = new GregorianCalendar(year,month - 1,day).getTime();
hireDay.setTime(newHireDay.getTime());
}
public void raiseSalary(double p)
{
double raise = salary * p / 100;
salary += raise;
}
public String toString()
{
return "Employee[name =" + name + ",salary =" + salary + ",hireDay =" + hireDay +"]";
}
}
8.调回是一种常见的程序设计模式,在这种模式中,可以指出某个特点事件发生时应采取的动作。
实例代码
测试类
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.Timer;
public class test {
public static void main(String[] args)
{
ActionListener li = new TimePrinter();
Timer t = new Timer(10000,li);
t.start();
JOptionPane.showMessageDialog(null, "退出?");
System.exit(0);
}
}
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
public class TimePrinter implements ActionListener{
public void actionPerformed(ActionEvent event)
{
Date now = new Date();
System.out.println("现在时间是:" + now);
Toolkit.getDefaultToolkit().beep();
}
}
原文地址:http://blog.csdn.net/zhurui_idea/article/details/44835813