基本 Java 对象 class 将对象返回为 null?
Basic Java object class returning objects as null?
我只有一个基本的Class封装食物,当我去我的客户class检查方法getName
、字符串和所有其他方法时,这一切returns 空。不知道这里出了什么问题。
public class Foods {
public String name;
public int calPerServing;
public int servingPerContainer;
Foods(String n, int c, int s){
n = name;
c = calPerServing;
s = servingPerContainer;
}
@Override
public String toString() {
return "Name: " + name + "\nCalories Per Serving: " + calPerServing
+ "\nServings Per Container: " + servingPerContainer;
}
public String getName() {
return name;
}
public int getCalPerServing() {
return calPerServing;
}
public int getServingPerContainer() {
return servingPerContainer;
}
public int getTotalCalories(){
return (calPerServing * servingPerContainer);
}
}
public class Client {
public static void main(String[] args) {
Foods chips = new Foods("chips", 10, 1);
System.out.println(chips.getName());
}
}
这是一个错字:
Foods(String n, int c, int s){
n = name;
c = calPerServing;
s = servingPerContainer;
}
应该是:
Foods(String n, int c, int s){
name = n;
calPerServing = c;
servingPerContainer = s;
}
我只有一个基本的Class封装食物,当我去我的客户class检查方法getName
、字符串和所有其他方法时,这一切returns 空。不知道这里出了什么问题。
public class Foods {
public String name;
public int calPerServing;
public int servingPerContainer;
Foods(String n, int c, int s){
n = name;
c = calPerServing;
s = servingPerContainer;
}
@Override
public String toString() {
return "Name: " + name + "\nCalories Per Serving: " + calPerServing
+ "\nServings Per Container: " + servingPerContainer;
}
public String getName() {
return name;
}
public int getCalPerServing() {
return calPerServing;
}
public int getServingPerContainer() {
return servingPerContainer;
}
public int getTotalCalories(){
return (calPerServing * servingPerContainer);
}
}
public class Client {
public static void main(String[] args) {
Foods chips = new Foods("chips", 10, 1);
System.out.println(chips.getName());
}
}
这是一个错字:
Foods(String n, int c, int s){
n = name;
c = calPerServing;
s = servingPerContainer;
}
应该是:
Foods(String n, int c, int s){
name = n;
calPerServing = c;
servingPerContainer = s;
}