[英]Constructor error, setter not working (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 = 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;
}
构造函数声明与类实例变量同名的局部变量。 不要在构造函数中 dexlare 本地人。
换句话说; 使用这个:“名称= n”。 不包含此内容:“字符串名称 = n”。
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);
}
}
你的本地变量,你必须设置实例变量 Self // https://telegram.me/javalike
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.