java的克隆
Employee.java
:
package clone;
import java.util.Date;
import java.util.GregorianCalendar;
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 byPercent){
double raise = salary * byPercent / 100;
salary+=raise;
}
public String toString(){
return "Employee[name="+name+",salary="+salary+",hireDay="+hireDay+"]";
}
}
cloneTest.java
package clone;
public class cloneTest{
public static void main(String[] args){
try {
Employee original = new Employee("John Q.Public", 50000);
original.setHireDay(2000, 1, 1);
Employee copy = original.clone();
copy.raiseSalary(10);
copy.setHireDay(2002, 12, 31);
System.out.println("original="+original);
System.out.println("copy="+copy);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
定时器的使用
package timer;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class TimerTest {
public static void main(String[] args) {
//构造这个类的一个对象将其 传递给Timer构造器
ActionListener listener = new TimePrinter();
Timer t = new Timer(10000,listener);
//第一个参数是发出通告的时间间隔,单位是毫秒
//第二个参数是监听器对象
//意思是 每隔10000毫秒通告listener一次
t.start();
//启动定时器,一旦启动成功,当到达指定的时间间隔时,定时器将调用监听器的actionPerformed方法
JOptionPane.showMessageDialog(null, "Quit program?");
System.exit(0);
}
}
//实现java.awt.event包中的ActionListener接口
//到达指定的时间间隔时,定时器就调用actionPerformed方法
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();
//获得默认的工具箱,发出一声玲响
}
}
内部类的一个例子
package innerClass;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class InnnerClassTest {
public static void main(String[] args) {
TalkingClock clock = new TalkingClock(1000,true);
clock.start();
JOptionPane.showMessageDialog(null, "Quit program?");
System.exit(0);
}
}
class TalkingClock{
private int interval;
private boolean beep;
public TalkingClock(int interval,boolean beep){
this.interval=interval;
this.beep=beep;
}
public void start(){
ActionListener listener = new TimePrinter();
Timer t = new Timer(interval, listener);
t.start();
}
public 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();
}
}
}
赏
使用支付宝打赏
使用微信打赏
若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏
扫描二维码,分享此文章