1

So in my code, I made a class named Pet, that would have both a default constructor and a non-default constructor that passes in String name, and int age of the pet.

public class Pet
{
// instance variables 
private int age;
private String name;

/**
 * Constructor for objects of class Pet
 */
    public Pet()
    {
        // initialise instance variables
        age = 0;
        name = "somePet";
    }

    public Pet(int age, String name)
    {
        this.age = age;
        this.name = name; 
    }
}

Then I created a class named petArray that would add to the array and print out the array...

public class PetArray
{
// instance variables 
private Pet [] petArray;

/**
 * Constructor for objects of class PetArray
 */
public PetArray()
{
    // initialise instance variables
    petArray = new Pet[5];
}

public void addPets()
{
    // put your code here
    Pet myPet = new Pet(4, "Spots");
    petArray[0] = (myPet);
    petArray[1] = new Pet(2, "Lucky");
    petArray[2] = new Pet(7, "Joe");
}

public void printPets()
{
    for (int i = 0; i < petArray.length; i++)
    {
        System.out.println(petArray[i]);
    }
}

}

But then, I get this in the terminal window when trying to print it out...

Pet@13255e3c Pet@171ac880 Pet@52185407 null null

LynnLove
  • 29
  • 2
  • 8

4 Answers4

0

You forgot to override toString() method inherited from Object.

In this case you can use something like this:

@Override
public String toString() {
    return (name + age);
}

Java compiler just does not know how to print it, you have to inform it :)

Treck
  • 69
  • 11
0

In your addPets() method you are only adding 3 objects to your petArray while there are 2 more spaces you need to fill as you declared that array to be a length of 5.

You could change the length of your array down to 3 or you could add 2 more objects, that should fix your problem.

And as stated above, adding the toString method will get rid of the addressing issues.

EfOhGee
  • 21
  • 5
0
class Pet {
    ...
    @Override
    public String toString(){
        // the string passed from here will be shown in console
    }
}
afzalex
  • 8,598
  • 2
  • 34
  • 61
0

Your output is fine according to your code. You have to override toString() method to print as per your requirement. Add this may be it will help.

@override
public string toString(){
 return "your required string"; // i.e : name or name+age
}
freak007
  • 88
  • 9