|
Consider a modified version of the class Circle:
import java.lang.Math;
public class Circle
{
// Accessor methods
public double x() { return m_x; }
public double y() { return m_y; }
public double radius() { return m_r; }
// Mutator methods
public void x(double v) { m_x = v; }
public void y(double v) { m_y = v; }
public void radius(double r) { m_r = r; }
// Operations/Attributes
public double getCircumference()
{ return 2 * Math.PI * m_r; }
public double getArea()
{ return Math.PI * m_r*m_r; }
// Data
double m_x, m_y; // coordinates of center
double m_r; // radius
}
|
where I've changed the accessor and mutator method names for illustrative
purposes.
Note: The Java standard
naming convention is to use getFoo and setFoo as names for the accessor and
mutator methods for an attribute named foo. I strongly recommend that you
follow this convention in all your Java code. (Note that the Sun Java
programmers did not initially follow this convention in early Java classes, but
they do in all current code.)
Method Overloading
This version of the Circle class contains several examples of method
overloading:
|
double x()
|
void x(double v)
|
|
double y()
|
void y(double v)
|
|
double radius()
|
void radius(double r)
|
Each overloaded method
shares a name (in our case, x,
y, or radius)
Method Signature
Each method is distinguished by its signature:
- its name, and
- the number, types and positions of
its arguments
- but not
its return type!
So, if you enter the two functions into the
Circle class:
public double getArea()
{ return Math.PI * m_r*m_r; }
public int getArea()
{ return Math.PI * m_r*m_r; }
You will get a compilation error:
Methods
'double Circle.area()' and 'int Circle.area()'
differ only in return type
|