为一个不含对象引用域的类启动克隆的示例:
运行结果为:
examples.cloning.Pair
( 5, 6 )
( 5, 6 )
1
/** An example class used to demonstrate how to
2
* enable cloning for a class without fields that
3
* contain object references..
4
*/
5
public class Pair implements Cloneable { //必须实现Cloneable,
6
7
private int a, b; //否则会抛出CloneNotSupportedException异常
8
9
/** Class constructor method
10
* @param initA Initial value for the first field
11
* @param initB Initial value for the second field
12
*/
13
public Pair( int initA, int initB ) {
14
a = initA;
15
b = initB;
16
}
17
18
/** Convert object to String representation
19
* @return The value of the array as a String
20
*/
21
public String toString() {
22
return "( " + a + ", " + b + " )";
23
}
24
25
/** The test method for the class
26
* @param args Not used
27
* @exception CloneNotSupportedException
28
* If clone not supported by
29
* inherited clone method
30
*/
31
public static void main( String[] args )
32
throws CloneNotSupportedException {
33
System.out.println( "examples.cloning.Pair" );
34
Pair x = new Pair( 5, 6 );
35
System.out.println( x );
36
37
Pair y = (Pair) x.clone();
38
System.out.println( y );
39
}
/** An example class used to demonstrate how to2
* enable cloning for a class without fields that3
* contain object references..4
*/5
public class Pair implements Cloneable { //必须实现Cloneable,6

7
private int a, b; //否则会抛出CloneNotSupportedException异常8

9
/** Class constructor method10
* @param initA Initial value for the first field11
* @param initB Initial value for the second field12
*/13
public Pair( int initA, int initB ) {14
a = initA;15
b = initB;16
}17

18
/** Convert object to String representation19
* @return The value of the array as a String20
*/21
public String toString() {22
return "( " + a + ", " + b + " )";23
}24

25
/** The test method for the class26
* @param args Not used27
* @exception CloneNotSupportedException28
* If clone not supported by29
* inherited clone method30
*/31
public static void main( String[] args ) 32
throws CloneNotSupportedException {33
System.out.println( "examples.cloning.Pair" );34
Pair x = new Pair( 5, 6 );35
System.out.println( x );36

37
Pair y = (Pair) x.clone();38
System.out.println( y );39
}运行结果为:
examples.cloning.Pair
( 5, 6 )
( 5, 6 )


浙公网安备 33010602011771号