This question already has answers here:
Assigning in Java?
                                
                                    (4个答案)
                                
                        
                                去年关闭。
            
                    
当此代码声明course2 = course1;时会发生什么情况?因为在那之后发生的事情我无法理解。如果我注释掉course2 = course1;我两次获得编程基础知识。

 

public Course(int courseID, String courseName) {
    ID = courseID;
    name = courseName;
}

public String getName() {
    return name;
}

public void setName(String newName) {
    name = newName;
}

public static void main(String[] args) {
    Course course1 = new Course(2531, "Programming Fundamentals");
    Course course2 = new Course(1285, "Algorithms and Analysis");

    System.out.println(course1.getName());

    course2 = course1;
    course2.setName("PF");
    System.out.println(course1.getName());
}


输出为:
编程基础
PF

最佳答案

course1是一个变量,它引用一个对象,比方说object1。

course2是另一个变量,它引用另一个对象,比方说object2。

调用course2 = course1时,使它们引用同一对象-object1

10-08 04:13