Object
Object类是java中所有类的基类也叫父类,所有类的顶层类。Object提供了一系列的方法,这些方法都被subClass继承,有些类为了完成一些功能重写了部分方法,如String、包装类等。
1. clone()
clone,”克隆“,这个词对我们来说很熟悉,就是copy。克隆技术就是将一个生物通过DNA复制技术产生另一个一模一样的生物,克隆体和原体虽然外表一模一样,但我们知道他们是两个对象。而Object的clone()方法也是同样的道理。我们可以通过使用该方法创建一个对象的克隆对象,克隆对象的属性值和原对象完全一致。其实就是相当于我们使用new方法再次创建了一个对象的后将其和属性赋相同的值。
两个对象除了初始化值一样外其实就是两个对象,克隆出的对象和普通实例一样可以调用属性和方法。
如果以上解释你还是不懂,我们还可以通过Cloneable接口中关于clone()的介绍来更清晰的认识clone()方法的作用:
(PS:如果我们想在自己定义的类中使用clone(),就需要先实现Cloneable接口,否则会发生CloneNotSupportedException异常)
package java.lang;
/**
* A class implements the <code>Cloneable</code> interface to
* indicate to the {@link java.lang.Object#clone()} method that it
* is legal for that method to make a
* field-for-field copy of instances of that class.
* <p>
* Invoking Object's clone method on an instance that does not implement the
* <code>Cloneable</code> interface results in the exception
* <code>CloneNotSupportedException</code> being thrown.
* <p>
* By convention, classes that implement this interface should override
* <tt>Object.clone</tt> (which is protected) with a public method.
* See {@link java.lang.Object#clone()} for details on overriding this
* method.
* <p>
* Note that this interface does <i>not</i> contain the <tt>clone</tt> method.
* Therefore, it is not possible to clone an object merely by virtue of the
* fact that it implements this interface. Even if the clone method is invoked
* reflectively, there is no guarantee that it will succeed.
*
* @author unascribed
* @see java.lang.CloneNotSupportedException
* @see java.lang.Object#clone()
* @since JDK1.0
*/
public interface Cloneable {
}
我们只需要理解第一段话就可以了:
A class implements the <code>Cloneable</code> interface to indicate to the {@link java.lang.Object#clone()} method that it is legal for that method to make a field-for-field copy of instances of that class.
大致意思就是一个类实现了Cloneable接口,
然后呢它就可以合理的使用clone()方法一个字
段一个字段的复制这个类的实例。
示例代码:
public class User implements Cloneable{ //Cloneable跟序列化接口一样,没有方法声明
private String account;
private String username;
private Integer age;
private BigDecimal balance; //BigDecimal是java.math下的数据处理类,银行数据使用它
//省略setter getter 方法
//带参构造
public User(String account,String username,Integer age,BigDecimal balance){
this.account= account;
this.username= username;
this.age = age;
this.balance = balance;
}
//方式1:重写clone方法,扩大其访问权限
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
//方式二:也可以将它做一个封装
/* public Object copySelf(){
Object obj = null;
try{
obj = this.clone();
}catch(CloneNotSupportedException e){
e.printStackTrace();
}
return obj;
}*/
}
测试类:
public class TestClone{
public static void main(String[] args) throws Exception{
User user = new User("0001","wsw",18,new BigDecimal(100.00));
Object clone = user.clone();
//或者使用封装方法 Object clone = user.copySelf();
System.out.println("是否为同一对象" + (user == clone));
System.out.println(user);
System.out.println(clone);
System.out.println(clone.getClass());
}
}
运行结果: