Java常用API——finalize方法 & clone方法

finalize方法 & clone方法

一、方法介绍

  • protected void finalize() throws Throwable:当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法
  • protected Object clone() throws CloneNotSupportedException:
    创建并返回此对象的一个副本

二、finalize方法

  • protected void finalize() throws Throwable:当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法
    在这里插入图片描述

三、clone方法常见问题之一

  • s1和s2指向的是同一个对象,所以不是对象的克隆
public class CloneTest {
    
    
	public static void main(String[] args) {
    
    
		Student s1 = new Student();
		Student s2 = s1;
	}
}

四、clone方法常见问题之二

  • 如果在没有实现 Cloneable 接口的实例上调用 Object 的 clone 方法,则会导致抛出 CloneNotSupportedException 异常
public class CloneTest {
    
    
	public static void main(String[] args) {
    
    
		Student s1 = new Student();
		
		//error:CloneNotSupportedException
		Object clone = s1.clone();
	}
}
  • API文档中的Cloneable接口
  • 如果一个接口内部是空的,那么称这个接口为标记接口
    在这里插入图片描述
  • 解决方案:在Student类中实现Cloneable接口并在Test类中将异常CloneNotSupportedException抛出
//Student.java
public class Student extends Object implements Cloneable {
    
    
	private String name;
	private int age;
	
	public Student() {
    
    
		super();
		// TODO Auto-generated constructor stub
	}
	
	public Student(String name, int age) {
    
    
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
    
    
		return name;
	}

	public void setName(String name) {
    
    
		this.name = name;
	}

	public int getAge() {
    
    
		return age;
	}

	public void setAge(int age) {
    
    
		this.age = age;
	}

	@Override
	public String toString() {
    
    
		return "Student [name=" + name + ", age=" + age + "]";
	}
	
	@Override
	protected Object clone() throws CloneNotSupportedException {
    
    
		// TODO Auto-generated method stub
		return super.clone();
	}
}
//CloneTest.java
public class CloneTest {
    
    
	public static void main(String[] args) throws CloneNotSupportedException {
    
    
		Student s1 = new Student();
		Object clone = s1.clone();
	}
}

五、clone方法常见问题之三

public class CloneTest {
    
    
	public static void main(String[] args) throws CloneNotSupportedException {
    
    
		Student s1 = new Student("张三", 18);
		
		//s2是通过s1克隆而来的
		Object clone = s1.clone();
		Student s2 = (Student)clone;
		
		//Q1:s1和s2是否是同一个对象?
		//A1:是的
		System.out.println(s1.toString());
		System.out.println(s2.toString());
		
		//Q2:s1和s2的内存地址是否一样?
		//A2:不一样
		System.out.println(s1 == s2);
	}
}
***执行结果:***
Student [name=张三, age=18]
Student [name=张三, age=18]
false

猜你喜欢

转载自blog.csdn.net/weixin_43796325/article/details/104516431