如果我在 java 中对同一个对象调用 new 两次会发生什么? [英] What happens if I call new on the same object in java twice?

查看:316
本文介绍了如果我在 java 中对同一个对象调用 new 两次会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以说我有一些这样的测试java代码:

So say I have some test java code like this:

class A(){
       int a = 0;
       public A{
             a = 1;
       }
 class B(){
       A object = new A(); //Object one
       A object = new A(); //Object two

我的问题是:在 A 类中,当我在对象上调用 new 运算符两次时会发生什么?它是否创建了一个新对象 A 并销毁了旧对象?还是会出错?它只是重置旧对象吗?

My question is: In class A when I call the new operator on object twice what happens? Does it create a new object A and destroy the old one? Or will it error? Does it just reset the old object?

我已经尝试了几次,但并不真正理解输出.

I have tried this a couple times and don't really understand the output.

推荐答案

它是第二个 A 对象.

第一个将在稍后被垃圾回收.

The first will be garbage collected sooner later.

注意,你也可以这样做

new A();
new A();

不将它们存储在变量中.它完全有效,将被执行.

without storing them in a variable. It's perfectly valid, and will be executed.

还要注意

A obj1 = new A();
A obj2 = obj1;

复制对象,但它是对同一对象的引用.显然,您也可以有 0 个引用.

does not copy the object, but it's a reference to the same object. You can also have 0 references, obviously.

这篇关于如果我在 java 中对同一个对象调用 new 两次会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆