I am completely new to Java.
I was practicing a code about a person eating some fruit. I have 3 classes
Fruit Class:
public class Fruit {
String fruitname = "grapes";
}
Person Class:
public class Person {
void eat(Fruit f) {
System.out.println("person is eating " + f.fruitname); // how can I do f.fruitname
}
}
Test Class:
public class TestFruit {
public static void main(String[] args) {
Person p = new Person(); // person object
Fruit f = new Fruit(); // fruit object
p.eat(f);
} // eat method of person class
}
output:
person is eating grapes
For accessing fields of a class, Object of that class is created.
My question is:
In Person
class, how can I access fruitname
field of Fruit
class (i.e., writing f.fruitname
) without instantiating Fruit
class in Person
class?
fruitname
is a data member of Fruit
class and instance member don't exist until object is created.
I have just started learning Java, and I am stuck here. Please help me to understand.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…