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.

JavaScript

}

JavaScript

}

JavaScript

}

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:

JavaScript

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().

JavaScript

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.

JavaScript

Welcome to Java!

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