user3813076
user3813076

Reputation: 1

Storing and getting values in an object JAVA

Need some help, I need to store values inside an object then be able to get them to print out or store in a variable. For example I wish to create a new object instance of dog and assign it the value Ralph. Then i will store this inside an array but how do you set the value and then access it? I have come up with the following so far.

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");
    }    
}

Upvotes: 0

Views: 60

Answers (2)

schlagi123
schlagi123

Reputation: 735

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());
    }    
}

Upvotes: 0

JamesB
JamesB

Reputation: 7894

Add a constructor to the dog class, taking the name as an argument:

public class dog extends Animal{

    private String name;

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

    public String getName() {
        return name;
    }
}

You would then use it like this:

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

or

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

P.S. Rename the class to Dog to follow standard Java naming conventions.

Upvotes: 1

Related Questions