java - 在Java中传递对象并尝试以多种方式更改它们

标签 java parameter-passing new-operator

我知道一点关于 Java 如何按值传递,以及如何将对象传递给方法可以更改对象的字段(例如 Car 类中的change1())。

但是,我的问题是为什么change2()和change3()不改变任何东西(尤其是change3())

public class question {

    public static void main(String[] args)
    {
        Car c1 = new Car(1000,"Hyundai");
        Car c2 = new Car(2000,"BMW");

        c1.change3(c1);
        c1.change3(c2);

        System.out.println(c1.name  + " "+ c1.price );
        System.out.println(c2.name +  " " + c2.price);
    }
}

class Car
{   
    int price;
    String name;

    Car(int p , String n)
    {
        this.price=p;
        this.name=n;
    }

    void change1(Car c)
    {
        c.price=0;
        c.name="Changed";
    }

    void change2(Car c)
    {
        c = new Car(999,"Honda");
    }

    void change3(Car c)
    {
        c = new Car(888,"Audi");
        c.price=80;
        c.name="xxx";
    }   
}

最佳答案

每次 JVM 执行 new 运算符时,都会创建一个新的对象/实例。您正在 change3(Car c) 方法中创建 Car 类型的新对象,并将该对象的引用存储到局部变量 c 中。此后,您在该 c 上设置的任何内容都会修改新对象,而不是您传递的引用的对象。

void change3(Car c) //receives the reference to the object you pass;
{
    c = new Car(888,"Audi"); //creates a new Car object and assigns reference to that **new object** to the variable c.
    c.price=80; //here, you're changing the price/name fields of different object.
    c.name="xxx";
}  

请注意,在 change1(Car c) 中,您不会创建新对象,但在 change2(Car c)change3(Car c) 中,您不会创建新对象。 ) - 你[明确]创建新对象。

关于java - 在Java中传递对象并尝试以多种方式更改它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60125350/

相关文章:

c++ - 关于删除 C++ 指针

c++ - 如何使用 UML 表示 C++ new() 运算符

java - 是否可以在 Android 手机上安装 java fx?

java - 如何从命令行 Java 应用程序更改命令提示符(控制台)窗口标题?

java - 使用 sc.hasNextLine() 进行无限循环

ruby - Ruby Win32API 参数是什么?如何传递空指针?

java - 如何打印位图 TM-T88V

scala - 如何在 Scala 中添加另一个参数时传递可变参数?

F# 将字符串传递给列表

c++ - 为什么 new 不需要转换为指针,即使 malloc 需要它?