clone克隆
程序员文章站
2023-12-28 17:36:34
...
java 代码
- public class Main implements Cloneable{
- String msg;
- public Main(String msg){
- this.msg = msg;
- System.out.println("init");
- }
- public Object clone()throws CloneNotSupportedException{
- return super.clone();
- }
- public boolean equals(Object obj){
- if(obj==this)return true;
- if(!(obj instanceof Main))return false;
- final Main temp = (Main)obj;
- if(this.msg.equals(temp.msg))
- return true;
- else
- return false;
- }
- public static void main(String[] args)throws Exception{
- Main main = new Main("sanyun");
- Main clone = (Main)main.clone();
- System.out.println(main==clone);
- System.out.println(main.equals(clone));
- System.out.println(clone.msg);
- }
- }
需要注意的几点:
1.必须实现Cloneable借口,否则会抛出CloneNotSupportException
2.Object的clone方法原形是protected,覆写时需要扩大访问权限public
3.clone方法并不会调用构造函数。
4Object colen方法的实现中会创建一个复制的对象,这个对象于原来的对象具有相同的值,但具有不同的内存地址