Syntax for Writing Your Own Class

Syntactically, a class has two basic parts:

  1. Attributes - the values tied to an object of that class. For instance, an object of class Point has an x coordinate and a y coordinate. The attributes of an object are stored in instance variables, which are also sometimes called fields.

    These are coded as declarations, and belong just after the opening curly brace that comes right after the public class line.

  2. Behaviors - the ways in which an object of that class can behave or be manipulated. The behaviors of an object are defined by the constuctors and other methods that belong to that class.

Basic Syntax

The basic syntax for a Java class is:


public class ClassName extends ParentClass
{
// declaration of instance variable(s)

private Class   instanceVariable;
...

public returnType methodName(class arg1, ...)
{
    statement;
    ...
    return x;   // where x is of type returnType
}
}
The code for the class should be in a file called ClassName.java.

More notes: