public class HelloWorld{
static class Sample {
private String n;
public Sample(String n){
this.n = n;
}
public String toString(){
return n;
}
}
public static void main(String []args){
Sample k = new Sample("A");
System.out.println(k);
stuff(k);
System.out.println(k);
}
public static void stuff(Sample k){
k = new Sample("B");
}
}
为什么打印 AA 而不是 AB?我是从一个关于 C# 的视频中看到这个的,但显然 java 也有它。
最佳答案
发生这种情况是因为您将 stuff
方法创建为静态。否则它会起作用。
使用此代码打印 A B。
public class HelloWorld{
static class Sample {
private String n;
public Sample(String n){
this.n = n;
}
public String toString(){
return n;
}
}
public static void main(String []args){
Sample k = new Sample("A");
System.out.println(k);
k=stuff(k);
System.out.println(k);
}
public static Sample stuff(Sample k){
return new Sample("B");
}
}
关于Java 方法从未到达 main 中的 (?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38009973/