Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

oop - accessing fields of a class in Java

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you're doing does not work because you're not declaring the member field as public:

public String fruitname = "grapes";

Only then you can even compile this:

System.out.println("person is eating " + f.fruitname);

Note that in Java fields are package private per default (see also). This means that the field can be private but in this case you can only access this field in classes which reside in the same package.


However, in general one creates getter and setter methods like this:

public class Fruit {

    private String fruitname = "grapes";

    public String getFruitname() {
        return fruitname;
    }

    public void setFruitname(String fruitname) {
        this.fruitname = fruitname;
    }
}

which will allow you to access the class member fruitname like this:

public class Person {
    public void eat(Fruit f) {
        System.out.println("person is eating " + f.getFruitname());
    }
}

Depending on your IDE you might be able to right click the field (or somewhere in the class) and find something like Generate.. > Getters & Setters which makes the whole act less annoying.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...