Skip to content
Advertisement

Method to output object details taken from main class

i have a created a main Pet class which contains the pet name and age and 2 sub classes for a Cat and dog which contain the breed, i am trying to create a method to display the information as a string but i am not sure how to pass the arguments to the method. When trying to use the speak method it says expected 3 arguments but received 0.

public class Pet {
private String name;
private int age;

public Pet() {
    name = "";
    age = 0;
}

public Pet(String petName, int petAge) {
    name = petName;
    age = petAge;
}

public String getName() {
    return name;
}

public int getAge() {
    return age;
}

public void setName(String petName) {
    name = petName;
}

public void setAge(int petAge) {
    age = petAge;
}

public String toString() {
    return "";
}

}

public class Cat extends Pet {
private String breed;

public Cat() {
    super();
    breed = "";
}

public Cat(String petName, int petAge, String catBreed) {
    super(petName, petAge);
    breed = catBreed;
}

public String getBreed() {
    return breed;
}

public void setBreed(String catBreed) {
    breed = catBreed;
}

public String toString() {
    return "Pet breed = " + breed;
}

static void speak(String petName, int petAge, String breed) {
    String str = "Miaow! i am " + petName + " a " + petAge + " year old " + breed;
}

}

public class PetTest {
public static void main(String[] args) {
    Cat cat1 = new Cat("Pixel", 4, "tabby");
    Dog dog1 = new Dog("Rex", 9, "terrier");
    System.out.println(cat1.speak());
    System.out.println(dog1.speak());
}

}

Advertisement

Answer

Your call to speak doesn’t match your method signature.

The way your Cat class is written, you’d have to pass petName, petAge, and breed to your speak method, like this:

System.out.println(cat1.speak(cat1.getName(), cat1.getAge(), cat1.getBreed()));

That’s probably not what you meant to do. Obviously, you want to populate these with the values you used to instantiate your class. To do that, your method signature for speak() should take no parameters, and instead use the values from the fields you defined in the class. On top of that, even if your method worked, it doesn’t actually return anything. From the usage, it looks like you want your speak method to return the appropriate string so that it can be printed with System.out.println().

public String speak() {
   return "Miaow! i am " + name + " a " + age + " year old " + breed;
}
   

To make it more clear, you can reference the fields of the class using the this operator, and use String.format to handle your string interpolation.

public String speak() {
   return String.format("Miaow! i am %%s a %%d year old %%s", this.name, this.age, this.breed);
}

Welcome to Java!

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement