public class Hotel {
private int roomNr;
public Hotel(int roomNr) {
this.roomNr = roomNr;
}
public int getRoomNr() {
return this.roomNr;
}
static Hotel doStuff(Hotel hotel) {
hotel = new Hotel(1);
return hotel;
}
public static void main(String args[]) {
Hotel h1 = new Hotel(100);
System.out.print(h1.getRoomNr() + " ");
Hotel h2 = doStuff(h1);
System.out.print(h1.getRoomNr() + " ");
System.out.print(h2.getRoomNr() + " ");
h1 = doStuff(h2);
System.out.print(h1.getRoomNr() + " ");
System.out.print(h2.getRoomNr() + " ");
}
}
なぜdo1はdoStuff(h1)を呼び出した後に変更されないのですか? 私はオブジェクトへの参照を渡す必要があり、メソッドでは新しいオブジェクトに置き換える必要があることを理解しています。scjpオブジェクトを渡す
はい、オブジェクトへの参照ですが、オブジェクトへの参照を保持する変数への参照ではありません。変数の値を変更するには、変数への参照を渡す必要があります(Javaでは直接使用できません) –
[http://www.java2s.com/Tutorial/SCJP/0020__Java-Source-And-Data-Type/PassingObjectReferenceVariables .htm](http://www.java2s.com/Tutorial/SCJP/0020__Java-Source-And-Data-Type/PassingObjectReferenceVariables.htm)および[http://www.coderanch.com/t/269485/java-プログラマー - SCJP /認証/合格オブジェクト参照変数](http://www.coderanch.com/t/269485/java-programmer-SCJP/certification/Passing-object-reference-variables) – diyesh