[英]Constructor error, setter not working (Java)
I am a java beginner, Why does this code return null ?我是一个java初学者,为什么这段代码返回null? What is wrong with the constructor ?
构造函数有什么问题? I set the name yet the sysout returns 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);
}
}
You declare new variables in the constructor instead of using the object variables.您在构造函数中声明新变量,而不是使用对象变量。
Change it to将其更改为
word(String n, int a, double c) {
name=n;
frequency=a;
rel_freq=c;
}
The constructor declares local variables that are the same names as the class instance variables.构造函数声明与类实例变量同名的局部变量。 Dont dexlare locals in the constructor.
不要在构造函数中 dexlare 本地人。
In other words;换句话说; use this: "name = n".
使用这个:“名称= n”。 Inatead of this: "String name = 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);
}
}
Your local variable, you must set the instance variable Self // https://telegram.me/javalike你的本地变量,你必须设置实例变量 Self // https://telegram.me/javalike
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.