I'm fairly new to Java and some of the concepts are still fuzzy, so I'm sorry if my question is a bit confusing.
I have a class Food, like so:
public Class Food {
// some unrelated methods and constructor
And then I have a bunch of subclasses of the Food class, all with a static variable "calories":
public Class Banana extends Food{
public static int calories = 100;
// more unrelated methods and the constructor
and:
public Class Chicken extends Food{
public static int calories = 300;
// more unrelated methods and the constructor
and so on...
As you can see, each subclass of Food has its own static "calories" variable with some unique value. It should also be noted that this calories variable needs to be changed sometimes; this is why it's not a const
.
I also have another class Eater:
public Class Eater {
// constructor:
public int mealcalories;
public Eater(Class c) {
this.mealcalories = c.calories;
As you can tell, I want to pass in the name of some Food subclass, e.g. Banana, into the constructor of an Eater class instance like this:
public Eater myEater = new Eater(Banana.class);
And then myEater's "mealcalories" variable should have a value of 100.
However, this isn't what's happening. I'm getting an error saying:
java: cannot find symbol
symbol: variable calories
location: variable c of type java.lang.Class
Can anyone help me on how to fix this and how to properly get the calories
variable from whatever Class c
I pass into it?
Note: this isn't actually what I'm coding, I've just simplified it to make it more understandable.