by Dinesh Thakur

Classes are the fundamental building blocks of any object-oriented language.

A class describes the data and behaviour associated with instances of that class. When a class is instantiated, an object is created: this object has properties and behaviour similar to other instances of the same class. The data associated with a class or object is stored in variables. The behaviour associated with a class or object is implemented by means of methods. Methods are similar to the functions or procedures of procedural languages such as C or Pascal.

A class can be defined as follows:


class First


       Body of the class


The keyword class is used to define a class. The keyword is followed by the name of the class (in the above example First). The body of the class is contained within curly brackets. The body consists of statements related to constructors, methods and variables.

Every class defined in Java is a child of the Object class.

Creating instance and class variables

A class usually contains variables and methods. Certain specific rules have to be followed for defining variables and methods within a class. This section deals with the definition of different types of variable, namely instance variables, constants and class variables.

Instance variables

Instance variables are declared and defined in almost the same way as local variables, the main difference being their location in the class definition. Variables are considered instance variables. if they are declared outside a method definition. It is customary to define instance variables just after the first line of the class definition.


A constant variable or constant is a variable whose value never changes.

Constants are used to define shared values for all the methods of an object so that object-wide values that will never change can be given meaningful names. In Java, only instance and class variables can be constants (not local variables). To declare a constant, the keyword final is used. It should be placed before declaration of the variable and should include an initial value for that variable, as shown in the following examples:

final float pi = 3.14:

final boolean debug = false;

final int maxsize = 40000;

Constants can be useful for naming various states of an object and testing them. For a test label that can be aligned left, right or centre, the values can be defined as constant integers.

final int LEFT = 0;

final int RIGHT = 1;

final int CENTER= 2;

Class variables

Class variables are global to a class and to all instances of that class. Class variables are used for communication between different objects within the same class. These variables are also used for tracking global states among a set of objects. The static keyword is used in the class declaration to declare a class variable. Some examples of this are given below:


static int sum;

static final int maxObjects = 10;