我对Java很新,有些概念仍然很模糊,所以如果我的问题有点令人困惑,我很抱歉。
我有一类食物,就像这样:
public Class Food {
// some unrelated methods and constructor
然后我有一堆Food类的子类,都有一个静态变量"卡路里":
public Class Banana extends Food{
public static int calories = 100;
// more unrelated methods and the constructor
和
public Class Chicken extends Food{
public static int calories = 300;
// more unrelated methods and the constructor
依旧......
正如您所看到的,食物的每个子类都有自己的静态卡路里"具有一些独特价值的变量。还应该注意的是,这种卡路里变量有时需要改变;这就是为什么它不是const
。
我还有另一个班级食者:
public Class Eater {
// constructor:
public int mealcalories;
public Eater(Class c) {
this.mealcalories = c.calories;
正如你所知,我想传递一些Food子类的名称,例如Banana,进入Eater类实例的构造函数,如下所示:
public Eater myEater = new Eater(Banana.class);
然后是myEater" mealcories"变量的值应为100.
但是,这不是发生了什么。我收到错误说:
java: cannot find symbol
symbol: variable calories
location: variable c of type java.lang.Class
任何人都可以帮我解决这个问题以及如何从我传入的calories
类中正确获取c
变量吗?
注意:这实际上并不是我编码的内容,我只是将其简化以使其更容易理解。