如何在java中访问对象的字段?

时间:2017-06-24 19:46:12

标签: java io

我道歉,这个问题已经回答过一次了。但是,解决方案对我没有帮助。

我制作的程序使用包含名称,ID和国家/地区的ArrayList。但是,我无法自己访问名称,ID和国家/地区,只能访问整个对象。我尝试使用animal.name并收到错误name cannot be resolved or is not a field。我尝试使用像getName()这样的方法来返回对象的名称,但是我得到了错误The method getName() is undefined for the type ArrayList<ANIMAL>。你能帮帮我吗?

这个类在调用时会在我试图访问的ArrayListfields内创建一个新对象:

    import java.io.*;

    public class ANIMAL implements Serializable {
        String nameA;
        String IDA;
        String countryA;

        public ANIMAL(String name, String ID, String country){
            nameA = name;
            String IDA = ID;
            String countryA = country;
        }

        public String getName(){
            return nameA;
        }
        public String getCountry(){
            return countryA;
        }
        public String getID(){
            return IDA;
        }
        }

2 个答案:

答案 0 :(得分:2)

你的动物类:

workbench.action.findInFiles

伪应用程序类(使用启动应用程序的主要方法):

public class Animal {

    private String name;
    private String id;
    private String country;

    public Animal (String name, String id, String country){
        this.name = name;
        this.id = id;
        this.country = country;
    }

    public String getName(){
        return name;
    }
    public String getCountry(){
        return country;
    }
    public String getId(){
        return id;
    }
}

打印:

public class MyApp {

    public static void main(String[] args) {
        List<Animal> list = new ArrayList<>();
        list.add(new Animal("British Bulldog", "12345", "UK"));
        list.add(new Animal("Boston Terrier", "12346", "USA"));
        list.add(new Animal("German Shepherd", "12347", "Germany"));
        // this is a for-each loop but basically you just need
        // to get an item from the list, list.get(i) would suffice
        for (Animal a: list) {
            System.out.println(a.getName());
        }
    }

}

另外:我冒昧地整理你的代码以匹配约定,查看差异并尝试理解它们。

答案 1 :(得分:0)

你的构造函数存在缺陷。

import java.io.*;

public class ANIMAL implements Serializable {
    String name;
    String ID;
    String country;

    public ANIMAL(String name, String ID, String country){
        this.name = name;
        this.ID = ID; 
        // String IDA = ID; doesn't assigns param ID to field ID of the class
        this.country = country; //same
    }

    public String getName(){
        return name;
    }
    public String getCountry(){
        return country;
    }
    public String getID(){
        return ID;
    }
}

希望这有帮助。