Java的Object类的------finalize()方法

finalize()方法

  • 当对象被判定为垃圾对象时,由JVM自动调用此方法,用以标记垃圾对象,进入回收队列。

  • 垃圾对象:没有有效引用指向此对象时,为垃圾对象。

  • 垃圾回收:由GC销毁垃圾对象,释放数据存储空间。

  • 自动回收机制:JVM的内存耗尽,一次性回收所有垃圾对象。

  • 手机回收机制:使用System.gc(); 通知JVM执行垃圾回收。

    Student类重写finalize()方法

    public class Student {
        //定义两个属性
        private String name;
        private int age;
    
        //定义 get set 方法 和有参无参构造
    
    
        public String getName() {
            return name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public Student() {
        }
    
        //重写finalize()方法
        protected void finalize() throws Throwable {
            System.out.println(this.name+"对象被回收了");
        }
    
    
    }
    

    执行方法

    public class TestFinalize {
        public static void main(String[] args) {
            //声明了4个对象
    //        Student aaa = new Student("aaa", 12);
    //        Student bbb = new Student("bbb", 12);
    //        Student ccc = new Student("ccc", 12);
    //        Student ddd = new Student("ddd", 12);
    //
    //        System.gc();
    //        System.out.println("垃圾被回收了");   //输出  垃圾被回收了  但是实际没有被回收
    
    
            new Student("aaa", 12);
            new Student("bbb", 12);
            new Student("ccc", 12);
            new Student("ddd", 12);
    
            System.gc();
            System.out.println("垃圾被回收了");  //这样子 垃圾就被回收了
    //        输出:
    //        ddd对象被回收了
    //        ccc对象被回收了
    //        bbb对象被回收了
    //        aaa对象被回收了
    //        垃圾被回收了
    
        }
    }
    
    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值