r/javahelp • u/Charlemagne-767 • Mar 05 '23
Solved Implementing a method within a toString method
I'm writing a class in which I have a class representing a circle. With the radius, two public methods were created to calculate the area and perimeter respectively. How might I call these methods in the toString method of the class? I have attached some of the class for visual representation.
Note: There is no good reason for you to down vote my posts.
0
Upvotes
2
u/ChaiTRex Mar 06 '23 edited Mar 06 '23
How to do toString
You would make a
toStringmethod. Inside thattoStringmethod, you'd use+to put things together into a newString. For example,"My name is " + this.getName() + " and my age is " + this.getAge()would be aStringyou could return.A few comments on the code you have
A circle with radius zero isn't that useful. A much more common circle is a unit circle (radius 1).
Methods in
Circlecan access theprivatefields of other instances ofCircle, so you can havepublic Circle(Circle other) { this.radius = other.radius; }.It's simpler to use
r * rthanMath.pow(r, 2).Because
Circleinstances already know their radius, theareaandperimetermethods should lose thestatic, have no arguments, and then usethis.radiusinstead ofr.Since you're using
getfor getting other information from theCircle, it would look more uniform if you named the methodsgetAreaandgetPerimeter.You should use proper indentation. With your starting code, that would be something like:
Notice that every time you have a
{, you make a new line and indent it four more spaces than before. Every time you have a}(which should generally be the only thing on that line), you go back to the previous amount of indentation.This gives the code a uniform and professional appearance, and it's easy to tell what's inside a class or method, because the stuff that's indented more than the class or method header is part of that class or method.
I'd also recommend that if you're just starting out, always use
this.in front of instance variables, like:This will always work, even when the method itself makes a new variable with the same name as the instance variable. It also makes it easy to tell at a glance that it's an instance variable.