构造函数错误,setter不工作(Java)
我是java初学者,为什么这段代码返回null?构造函数有什么问题?我设置了名称,但sysout返回null构造函数错误,setter不工作(Java),java,Java,我是java初学者,为什么这段代码返回null?构造函数有什么问题?我设置了名称,但sysout返回null public class word { String name; int frequency; double rel_freq; word(String n, int a, double c) { String name = n; int frequency = a; double rel_freq =
public class word {
String name;
int frequency;
double rel_freq;
word(String n, int a, double c) {
String name = n;
int frequency = a;
double rel_freq = c;
}
public static void main(String[] args) {
word maxwell = new word("bobo", 25, 40);
System.out.println(maxwell.name);
}
}
在构造函数中声明新变量,而不是使用对象变量。
换成
word(String n, int a, double c) {
name=n;
frequency=a;
rel_freq=c;
}
构造函数声明与类实例变量同名的局部变量。不要在构造函数中使用局部变量 换言之;使用这个:“name=n”。其中包括:“字符串名称=n” 如果是局部变量,则必须设置实例变量Self //
package iran;
public class word {
String name;
int frequency;
double rel_freq;
word(String n, int a, double c) {
this.name = n;
this.frequency = a;
this.rel_freq = c;
}
public static void main(String[] args) {
word maxwell = new word("bobo", 25, 40);
System.out.println(maxwell.name);
System.out.println(maxwell.frequency);
System.out.println(maxwell.rel_freq);
}
}