java中对“对象”以及“引用”的理解

一,前言

    在java学习中,理解对象以及对象的引用是非常重要的。不要把对象与对象的引用混为一谈。

二,分析对象与对象的区别

    

int height = new Rectangle().height;                                                                       

 //This statement creates a new Rectangle object and immediately gets its height. In essence, the statement calculates the default height of a Rectangle. Note that after this statement has been executed, the program no longer has a reference to the created Rectangle, because the program never stored the reference anywhere. The object is unreferenced, and its resources are free to be recycled by the Java Virtual Machine.

As with instance fields, objectReference must be a reference to an object.

You can use a variable name, but you also can use any expression that returns an object reference.

The new operator returns an object reference, so you can use the value returned from new to invoke a new object's methods:

new Rectangle(100, 50).getArea()

The expression new Rectangle(100, 50) returns an object reference that refers to a Rectangle object.

As shown, you can use the dot notation to invoke the new Rectangle's getArea() method to compute the area of the new rectangle.


//创建一个Demo类
public class Demo
{
	public Demo{}//默认构造方法
}

接下来,我们用Demo类来创建一个对象。

Demo demo = new Demo(); 

这一条语句,其中包括了四个动作:

    1)右边的“new Demo”,是以Demo类为模板,在堆空间里创建一个Demo对象。

    2)末尾的()意味着,在对象创建后,立即调用Demo类的构造函数,对刚生成的对象进行初始化。

    3)左边的"Demo demo"是创建了一个Demo类的引用变量,它存放在栈空间中。也就是用来指向Demo对象的对象引用。

    4)"="操作符使对象引用指向刚创建的那个Demo对象。

上条语句还可以写成:

Demo demo;//在栈上创建一个Demo类的对象引用
demo = /*将对象引用指向对象*/ new Demo()//在堆上创建一个Demo类的对象

用图表示:


三,对象引用与对象之间的关系

    1)从对象引用出发:

            一个对象引用可以指向一个对象

Demo demo; //一个对象引用
demo = new Demo() //一个对象引用指向一个对象

            也可以不指向对象

Demo demo; //创建对象引用,但没有指向对象

    2)从对象出发:

            一个对象可以一个对象引用引用   //(感觉引用和指向没差)

Demo demo; //创建对象引用
demo = new Demo() //创建对象,并被一个对象引用 指向

            也可以被多个对象引用同时引用

Demo demo1, demo2, demo3;//创建多个   对象引用
demo1 = new Demo();
demo2 = demo1;
demo3 = demo2;//创建对象,被多个   对象引用   指向
转载于  https://blog.csdn.net/qq_26805137/article/details/52945688

      

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值