在对象JAVA中存储和获取值

时间:2014-07-07 15:50:32

标签: java arrays object

需要一些帮助,我需要将值存储在对象中,然后才能将它们打印出来或存储在变量中。例如,我希望创建一个dog的新对象实例,并为其赋值Ralph。然后我将它存储在一个数组中,但是如何设置该值然后访问它?到目前为止,我已经提出了以下建议。

public class Animal {
    public static void main(String[] args) {
       dog d = new dog();
       AnimalList dogie = new AnimalList(d);
    }

}



package animal;
public class dog extends Animal{
   String name = "Ralph";
   int number = 1;
    public dog(){

    }
}


package animal;
import java.util.*;
public class AnimalList  {
    ArrayList animalList = new ArrayList();
    public AnimalList(Animal a){
        animalList.add(a);
        System.out.print("object added");
    }    
}

2 个答案:

答案 0 :(得分:1)

将一个构造函数添加到dog类中,将名称作为参数:

public class dog extends Animal{

    private String name;

    public dog(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

然后你会像这样使用它:

dog myDog = new Dog("Ralph");
//...
myDog.getName(); // <-- will return "Ralph"

dog myDog = new Dog("Fido");
//...
myDog.getName(); // <-- will return "Fido"

P.S。将类重命名为Dog以遵循标准Java命名约定。

答案 1 :(得分:0)

public class Animal {
    private String name;

    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }

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


    public static void main(String[] args) {
       dog d = new dog();
       AnimalList dogie = new AnimalList(d);
    }
}


package animal;
public class dog extends Animal{
    int number = 1;
    public dog(String name){
        super(name);
    }
}


package animal;
import java.util.*;
public class AnimalList  {
    ArrayList animalList = new ArrayList();
    public AnimalList(Animal a){
        animalList.add(a);
        System.out.print(a.getName());
    }    
}