A class can be viewed as a collection of data (also referred to as state) and code to operate on that state.

The data is stored in fields, and the code is organized into methods.

This post covers fields and methods, the two most important kinds of class members. Fields are like variables of a class and methods are like functions of a class.

package javaapplication39; public class Circle { // A class field public static final double PI = 3.14159; // A useful constant // A class method: just compute a value based on the arguments public static double radiansToDegrees(double radians) { return radians * 180 / PI; } // An instance field public double r; // The radius of the circle // Two instance methods: they operate on the instance fields of an object public double area() { // Compute the area of the circle return PI * r * r; } public double circumference() { // Compute the circumference // of the circle return 2 * PI * r; } public static void main(String[] args) { Circle c = new Circle(); double radians = 8; double deg = c.radiansToDegrees(radians); System.out.println(deg); c.r = 5; double area = c.area(); System.out.println(area); } }

In defining the PI, we have used a static declaration. If present, this modifier specifies that the field is associated with the defining class itself rather than with each instance of the class.

## Leave a comment