java声明式对象和new对象的区别

首先看代码:

VerificationCode verificationCode ;//声明式对象

verificationCode= verificationCodeMapper.selectLatestVerificationCode(email) ;//声明式对象

VerificationCode verificationCode =new  VerificationCode();//new对象

总结:声明式对象只是一个该对象类型的变量或者说是引用没有真正实例化,第二段代码只是把查找到的该类型对象返回来给这个变量。如果没有第二段代码,去引用这个变量的方法的时候可能会出现空指针异常。并且该对象存活时期是在栈上,执行完就死亡了(不知道是不是真的)。

new对象是直接实例化了嘛然后分配在堆上,存活时期看垃圾回收器。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
public class Rectangle { //声明矩形类 int xTopLeft; //左上角横坐标 int yTopLeft; //左上角纵坐标 int xBottomRight; //右下角横坐标 int yBottomRight; //右下角纵坐标 int id; //唯一编号 static int nextId; //表示下一个对象唯一编号 void move(int xOffset,int yOffset){//移动:xOffset、yOffset 分别是横向、纵向位移 xTopLeft = xTopLeft + xOffset; yTopLeft = yTopLeft + yOffset; xBottomRight = xBottomRight + xOffset; yBottomRight = yBottomRight + yOffset; } } class Example{ public static void main(String[] args){ Rectangle rect1 = new Rectangle(); //创建第1 个矩形对象 rect1.xTopLeft = 100; //设置左上角横坐标 rect1.yTopLeft = 100; //设置左上角纵坐标 rect1.xBottomRight = 300; //设置右下角横坐标 rect1.yBottomRight = 150; //设置右下角纵坐标 rect1.id = Rectangle.nextId; //设置矩形对象的唯一编号 Rectangle.nextId++; //生成下一个唯一编号 Rectangle rect2 = new Rectangle(); //创建第2 个矩形对象 rect2.xTopLeft = 200; rect2.yTopLeft = 100; rect2.xBottomRight = 500; rect2.yBottomRight = 200; rect2.id = Rectangle.nextId; //设置矩形对象的唯一编号 Rectangle.nextId++; //生成下一个唯一编号 rect1.move(10, 20); //将第一个矩形对象移动:横坐标移动10,纵坐标移动20 System.out.println("编号为"+rect1.id+"的矩形对象的周长与面积分别是"); int width1 = rect1.xBottomRight - rect1.xTopLeft; //第1 个矩形对象的宽度 int height1 = rect1.yBottomRight - rect1.yTopLeft; ///第1 个矩形对象的高度 System.out.println((width1 + height1)*2);//输出rect1 引用对象的周长 System.out.println( width1 * height1 );//输出rect1 引用的对象的面积 System.out.println("编号为"+rect2.id+"的矩形对象的周长与面积分别是"); int width2 = rect2.xBottomRight - rect2.xTopLeft; int height2 = rect2.yBottomRight - rect2.yTopLeft; System.out.println((width2 + height2)*2);//输出rect1 引用对象的周长 System.out.println( width2 * height2 );//输出rect1 引用的对象的面积 }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值