Class Syntax
/**
* Description of the class
*/
accessSpecifier class ClassName
{
///////////////////////////
// Data Members (fields)
///////////////////////////
accessSpecifier fieldType fieldName; // description of field
//////////////////
// Constructors
//////////////////
/**
* Describe what constructor does
* @param p1 describe the first parameter
* @param p2 describe the second parameter
*/
accessSpecifier ClassName(paramType paramName, paramType paramName)
{
// constructor body
}
/////////////
// Methods
/////////////
/**
* Describe purpose and use of the method.
* @param p1 describe the first parameter
* @param p2 describe the second parameter
* @return describe the value returned
*/
accessSpecifier returnType methodName(paramType paramName, paramType paramName)
{
// method body
}
}
Example
/**
* A Human has a name and an age. A human's name can be changed at any time.
* A human's age only changes when the human has a birthday.
*/
public class Human {
private String name; // the human's name
private int age; // the human's age
/**
* Creates a human with the given name. The human starts out at age 0.
* @param initName the name to give the human
*/
public Human(String initName) {
name = initName;
age = 0;
}
/**
* Returns the name of this human.
* @return the name of the human
*/
public String getName() {
return name;
}
/**
* Returns the age of this human.
* @return the age of the human
*/
public int getAge() {
return age;
}
/**
* Changes the name of this human to the new name given.
* @param newName the new name for the human
*/
public void setName(String newName) {
name = newName;
}
/**
* Causes the human to have a birthday (i.e., adds a year to the age).
*/
public void haveBirthday() {
age = age + 1;
}
}