public class Test1 { public static void main(String[] args) { Test1 test = new Test1("ABC"); System.out.println(test.text.toLowerCase()); } private String text; public Test1(String s) {
String text = s;
}}
为什么会引起这个错误?
String text = s;
}}
为什么会引起这个错误?
text = s;
}}
此text非彼text!
String text = s;
}}
上面定义的text没有用到。你在构造方法里又实例一个。他们是不同的。你每次实例都是一个新的对象。
一般构造方法都要有个无参的,据说是规范
public Test1(){}
this.text = s;
}}
public Test1(String s) {
String text = s;
}
这个构造方法里的text和
private String text;
是两个不同的变量,方法里的text的作用域是{}内,而成员变量的作用域是整个包内(默认情况下),如果在方法内或方法传递的参数内又定义了同成员变量同名的变量明时,Java会用this.变量名 来代替成员变量,因此你的构造方法应该这样写public Test1(String s) {
this.text = s;
}