finalize() 方法
垃圾回收方法
/
/
package jichu9;
public class Dog {
public Dog dog=null;//后面新增的属性
//finalize方法重写
protected void finalize() throws Throwable {
System.out.println("我被垃圾回收了 "+name);
}
public boolean equals(Object obj){
if (this==obj){
return true;
}
if (obj instanceof Dog){
Dog d=(Dog)obj;
if (this.name.equals(d.name)){
if (this.color.equals(d.color)){
if (this.age==d.age){
return true;
}
}
}
}
return false;
}
private String name;
private String color;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
/
package jichu9;
public class Test2 {
public static void main(String[] args) {
Dog d1=new Dog();
d1.setName("旺财");
Dog d2=new Dog();
d2.setName("猪猪");
System.gc();//立即回收促进方法
System.gc();
System.out.println("-----");
d1=d2;//把d2的内存地址给了d1,那d1就也指向d2的内存地址
d2=null;//d2指向的是空的内存;但是d1还指向那个内存,所以只有旺财被回收
//d2=null;
//d1=null;//这样就全部回收了
System.gc();
System.gc();
}
}
/
Dog d1=new Dog();
d1.setName("旺财");
Dog d2=new Dog();
d2.setName("猪猪");
d1.dog=d2;//d1里的dog属性指向d2;所以都不会被回收
d2=null;//都不会被回收
d1=null;//旺财会被回收
System.gc();
System.gc();
/
/
/
/
/
/
/
final关键字
final(最终的意思)
final修饰在类上,类就不可以继承了(最终类)
final写在属性上,那属性就是常量
public final String name=“AVBFD”;
public final void method(){}
如果final写在方法上,那方法不可以重写,(最终方法)