Classes in Java
Objects with the same structure and behavior are grouped into classes.
A class defines:
- Fields (data items or attributes) of each object in the class.
- Methods (functions) of each object, which perform some operation on a set
of input parameters and on the data items of the object, and which optionally
return a value or object.
- Fields which are shared between all objects in the class.
They are declared static.
When a static field is also declared final it defines a constant.
- Methods which are shared between all objects in the class.
They are called class methods, and can only use the static fields,
not the fields of each object. They are declared static.
There can be confusion between parameters or local variables and
an object's fields. The this prefix is used to refer explicitly
to a method or field of the current object.
Example:
class Point {
public int x, y;
/* default constructor */
public Point() {
x = 0; y = 0;
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
class Rectangle {
public Point origin, corner;
public int Width() {
return corner.x - origin.x;
}
public int Height() {
return corner.y - origin.y;
public int Circumference() {
return 2 * (Width() + Height());
}
public int Surface() {
return Width() * Height();
}
}