步骤
1、创建克隆类和属性
2、写构造器
3、继承 implements Cloneable
4、重写clone()方法
5、抛出异常或者抓异常
6、向下转型
7、重写toString 方法
package Demo21;
public class CloneShallow {
public static void main(String[] args) throws CloneNotSupportedException {
Car car1 = new Car(1,new Engine(221,"v8"),new Tire(331,"米其林"));
Car car2 = (Car) car1.clone();
System.out.println(car1.toString());
System.out.println(car2.toString());
}
}
class Car implements Cloneable{
public int cid;
public Engine engine;
public Tire tire;
public Car(int cid, Engine engine, Tire tire) {
this.cid = cid;
this.engine = engine;
this.tire = tire;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return "Car{" +
"cid=" + cid +
", engine=" + engine +
", tire=" + tire +
'}';
}
}
class Engine {
public int eid;
public String eName;
public Engine(int eid, String eName) {
this.eid = eid;
this.eName = eName;
}
}
class Tire {
public int tid;
public String tName;
public Tire(int tid, String tName) {
this.tid = tid;
this.tName = tName;
}
}