← 返回首页
JavaSE系列教程(十八)
发表时间:2019-12-21 17:54:00
讲解什么是引用和匿名对象

1.什么是引用

引用是对象的别名,引用不等于对象。

回顾以下代码:

public class Human {

    String name;
    String gender;
    int age;

    Human(){
      System.out.println("一个人从世界上诞生了");
    }
    //这里出现了构造方法重载。
    Human(String name,String gender,int age){
        this(); //在构造方法中使用this关键字调用本类的其它构造方法。
        this.name = name;
        this.gender = gender;
        this.age = age;
    }
    public void eat(){
        System.out.println(this.name + "正在吃...");
    }

    public void think(){
        System.out.println(this.name + "正在思考人生中...");
    }

    public static void main(String[] args){
        Human h = new Human("张三","男",18); //这里h就是引用,Human是引用类型。
        h.eat();
        h.think();
    }

}

运行结果:
一个人从世界上诞生了
张三正在吃...
张三正在思考人生中...

我们把Human h = new Human("张三","男",18);这句话以庖丁解牛的方式分解开来,包含以下几个部分,如图所示:

引用不等于对象,在一段程序代码中,一个引用变量可以在不同的时间指向不同的对象,甚至是不指向任何对象(称为空引用)。 例如以下代码:

Human h = new Human("张三","男",18);
h.think();  //此时h指向张三对象
h = new Human("李四","女",20);
h.think(); //此时h指向李四对象
h = null;  //此时h不指向任何对象
h.think();  //这里会抛出 NullPointerException

//程序执行结束时,内存中一个引用(h引用),两个对象(张三和李四)。

2.什么是匿名对象

我们把没有引用指向的对象称为匿名对象。

例如:

public static void main(String[] args){
     //下面就是一个匿名对象
     new Person("王五","男",19).think();
}

==注意:由于匿名对象没有引用指向它,所以在程序运行过程中,一旦出现内存不够用的情况,会优先被JVM的垃圾回收器回收以释放内存空间。==

小结:

1).引用是对象的别名,引用不等于对象。

2).没有引用指向的对象是匿名对象。