• Post Reply Bookmark Topic Watch Topic
  • New Topic

need help with a lab question  RSS feed

 
ivan auyoung
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi, im very new to the forum and i want to get help for one of my lab question im struggle on. thank you
so this is the whole question:
Write a class called Animal that has the following members:
1. an instance field of type float called mass.
2. an instance field of type String called name for the species.
3. an instance field of type int called legs.
4. a setter method for the field mass.
5. getter methods for the three field.
6. a constructor that takes one argument of type String and uses it to initialise the field name.The other two fields should be set to 0.
7. another constructor that takes three arguments of type float, String and int and initialises the three arguments.
8. Add a method that overrides the toString method.This method should construct a string representation of the class that includes the values of all three fields.
9. Write a class called TestAnimal with a main method that creates an Animal object using the three argument constructor;initialising it to name "snail",mass 3.5,and legs 1;and then prints out the object using the toString method.

ive struggle with the last two part of the question. what i already done is here:





im quite confuse with how to overide the toString method, not sure if what i did i correct, and also print out the object with toString method.

Thank you
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch.

It seems that you're well on your way. The toString method you have is a good start, but it only uses one of the 3 attributes of the Animal class. #8 says it should use all 3.

As #9, what you have is correct. The System.out.println statement will cause the toString method to be called, and its result will be printed out.

Note that #4 talks only of a setter method for the mass - you also have a setter method for the name (which is OK in general, but since your code presumably should do exactly what the question asks, you may want to remove it).

There's a problem in lines 22 and 23 - compare them with lines 27 and 29.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!