by Dinesh Thakur Category: Introduction to Java

Objects and classes are the essential concepts in OOP as they are what we use for writing our programs. Java objects may be both physical and logical entities, but classes are only logical entities.

In the real world, you'll often find many individual objects all of the same kind.All the objects that have similar properties and similar behavior are grouped together to form a class.

A class is a fundamental building block of all Java programs. In other words we can say that a class is a user defined data type and objects are the instance variables of class. It is a logical way to group fields that hold values (data) and associated methods that operate on those fields into a single unit. The class provides the structure or blueprint for creating objects. It describes how an object looks and operates. It helps us to create a user-defined data type.

In Java, you cannot write any code without declaring a class. All classes must be defined by a class definition which consists of two parts: class header and class body.

The class header declares the names of the class along with other information about the class such as a name of its superclass, whether it implements any interfaces, access specifier that determines the visibility, modifiers which declares whether the class is abstract or final. The class body enclosed within braces and consists of fields, methods, constructors and other declarations. At its simplest level, the class takes the following form

Class Specification

The items enclosed in the square brackets are optional.

Class Header

A class definition begins with a class header that minimally consists of a keyword class followed by a class name. The keyword class informs the compiler that you are specifying a class. It is followed by a className which refers to the name of the class given by the programmer. The name of the class should be such that it should convey the purpose for which it designed. The class name must be legal Java identifier and by convention begins with a capital letter. For example: Suppose you want to define a class 'Rectangle.' Then it's a class header in the purest form will look like

class Rectangle

Class Body

The class body which enclosed in curly braces contains the declarations of the elements that make up the objects of the class. Generally, a class body includes fields and methods. These elements are known as the members of the class. The field declaration provides the state of the class, and its objects and method declaration provides the behavior of the class and its objects. In addition to the field and method declarations, the class may also include constructors for initializing new objects, initializers, nested classes, etc.

Field Declaration

Fields are the named variables such as primitives and reference variables. The purest form of field declaration consists of the field type followed by the field name. Its syntax is

type fieldname;

Where type can be any of the primitive types such as int, char, float, boolean, etc. or can be a reference type such as an object, array, string, etc. The fieldName corresponds to the name of the field which follows the same rules and conventions as that of identifiers.

For examples: The following declaration.
int length;
declares a fieldname length of type int.
Some other examples are
double salary; // salary is a variable of type 'double.'
String name; // name is a variable of ref. type 'String.'
Point P;// p is a variable of reference type 'point.'

Defining Methods

Methods are indeed the heart and soul of the Java programs. A method is a self-contained block of code that performs a specific task. They provide a way of defining the behavior(s) of an object, i.e., what the object does. They serve the same purpose in Java that functions do in C and C++. Methods serve to break up large and complex calculations that might involve many lines of code into more manageable chunks. All execution that takes place in any application is within a method.

Just like a class definition, the method definition consists of two parts: the method header and the method body. In its purest form, the method can take the following form.

Defining Methods

Method Header

A method definition begins with a method header that minimally consists of the method's return type followed by the method name and optional parameter list enclosed in parentheses.

The returnType in a method header specifies the type of value if any, that the method returns. It may include a primitive data type or reference type. If the method does not return a value, then the return type must be void. The methods with return type void execute the sequence of statements given in their bodies. Following the returnType is the methodName in the method header that specifies the name of the method. It follows the same rules and conventions as that of identifiers.

Then following the method's name is the method's parameter list which must enclose in parentheses. A parameter is a variable that temporarily stores data values known as arguments that are being passed to the method whenever it called. A parameter list may contain zero or more parameters. Each argument passed to the method must have its corresponding parameter. If no arguments passed to the method, then the parentheses remain empty. The parameter specifications, if any, each consists of a type and a name and are separated from each other by commas. The parameter list takes the following form,

(datatype varNamel, datatype varName2,)

For example: Suppose you want to create a method named setData that is used to set values for the length and breadth of the field of class Rectangle. Let l and b its two parameters of int type that stores the length and breadth information of the rectangle respectively. Since this method only assigns a value and does not return any value, so the return type for the setData() method void. The method header will look like,

int area(int l,int b)

Note: The parameters specified in the method header are also known as formal parameters, and the arguments that passed to the method are also known as actual parameters.

Method Body

The method's body enclosed in a pair of curly braces consists of local variables and constant declarations for use within the method and sequence of executable statements that take some action when the method invoked. For example, the following method sets the length and breadth fields of the Rectangle class,

void setData(int l,int b){
   length l;

   breath b;

The setData() method's body enclosed within a pair of curly braces consists of two executable statements.

Returning Value from Method

A method header contains a return type that specifies the type of value that the method returns on completion of its task. To return a value from the method, the return statement used. Its syntax is


Here, expr is a variable, constant value or an expression.
The data type of the value that the expression evaluates to must match the method's return type or must be compatible with the method's return type. If this does not hold, then the compiler produces an error message.

On execution of the return statement, the program control immediately returns to the point where the method called. If the expression is part of the return statement, then the value of that expression is returned as the value of the method invocation. For example: Suppose you want to create a method area that calculates the area of the rectangle whose length and breadth are given and returns the area as an integer. The method area() looks like.

int area () {
rectArea = length*breadth;
   return rectArea;

Note: You can enclose an expression being returned in parentheses especially if the expression is complicated.
Any method with a return type void does not return a value. Since it does not return any value so you can either omit the return statement or use the keyword return by itself to end the execution of the method,


If you try to return a value from a method that is declared void, you get a compiler error. However, any method that is not declared void must contain a return statement with a corresponding return value.
There can be more than one return statement in a method. For example:

int minirnum(int a, int b) {
      return a;
      return b;

Method By Example

Now let us take a look at a method created to find the minimum of two integers. This method named min has two parameters x and y of type int which corresponds to the first and the second's number respectively. It calculates the minimum of two given integers which is returned by the method.

Method by Example

 Class By Example

After understanding how to create a class definition, fields and methods, now let us put them all together into an example. In this example, we are creating a class Rectangle which is as specified below

Class By Example

The class Rectangle specified above has four members. The variables 1ength and breadth are the fields, and setData() and area() are the methods. The setData() method used for assigning the values to the data members length and breadth. The area() method is used to calculate the area of the rectangle and return its value.
Some other valid class definitions show as follows,

valid class definitions

The class Employee has three field members namely empId, eName, basSal and three methods namely inputData(), displayData() and grossSal().
The class Studen t has three field members namely rollNo, name and marks and four methods namely verifyMark(), inputData(),display() and calculate().
The Class Library has four field members namely bookld, bookName, authorName, and totalBooks and four methods namely issue(), pending (), input() and display().

Creating Objects of a Class

Consider an example of an architect of a house who specify a design of a house, i.e. how it looks like, but doesn't build any house. By this design, a builder can build one or more houses. Similarly, a class specifies the format for creating objects. The mere definition of a class doesn't create an object. It only describes how the objects looked like when they created. So a class definition is just a template or a blueprint based on which one or more objects which are real-world entities can create.

Java provides several ways to create an object from a class. One of the most common and simplest ways is to use the new keyword to create an object of the class and then assign the resulting object to the reference variable. A reference variable is a symbolic name that is used to reference an object. In general, the syntax for creating an object of a class is as shown below,

ClassName refVariableName = new ClassName([argument list]);
This statement is a combination of three parts: declaring a reference variable, creating an object and assigning an object to a reference variable. To explain this, let us consider an example, where we want to create an object of the Rectangle class.

object of the Rectangle class

1. Declaring a reference variable 2. Creating an object 3. Assigning an object to a reference variable

Declaring a reference variable

When we create a class, a new datatype created. You can use this type to declare objects of that type. So to declare a reference variable of class type Rectangle that holds a reference to a Rectangle object, we use the similar syntax that begins with a class name followed by a reference variable name,
ClassName refVariableName;
For example, consider the statement,
Rectangle myRect; //declares a reference to object
This statement declares a reference variable myRect that can store a reference (address) of an object of type Rectangle. At this point, no object created, and no memory allocated for an object. So the reference variable myRect contains the value null. The null keyword is a special literal value that is a reference to nothing. If you attempt to use myRect now in the program, then the compiler generates an error message.

Result of declaring on object

Creating an Object

Declaring a myRect reference variable to hold Rectangle's object does not however create the object itself. To actually create an object, you must use the new operator. This new operator is followed by the classname whose object you want to create (i.e. Rectangle) and an optional argument list enclosed in parentheses. For example, in the statement,
new Rectangle () ;
The operator new dynamically allocates memory for a Rectangle object which consists of fields length and breadth. The operator new then returns the address of the newly allocated memory. Do not worry about the parentheses at the end of the preceding statement. We will talk about their significance when discussing constructors.

Assigning an Object to a reference variable

In the third part, the object is linked with the reference variable. This is accomplished using the assignment statement as follows,
myRect = new Rectangle(); //allocate a Rectangle object
This statement simply assigns the newly created object of the Rectangle class to the reference variable myRect. In other words, address of the memory allocated to the Rectangle object is assigned as the value of the reference variable myRect.

execution of statement

Creating an object from a class is also known as instantiation. Thus objects are often called instances. Similarly a few more examples are
Employee el = new Employee();
Student stu new Student();

Accessing an Object Fields and Methods

After creating an object of a class, there must be some way to access its fields and methods. To access the fields and methods within its class, you have to write the field name or the method name followed by parentheses and list of arguments, if any. For example: In the Rectangle class, the fields length and breadth in the area () method can be accessed by simply writing their names. However, if you want t6 access the fields and methods outside the class, you have to use the dot operator (.) also known as object member access operator. Its syntax is For accessing fields,


For accessing methods,


The notation to access method states that first specify the object reference variable (ObjectRefVar) followed by a dot operator(.) and then the method name (methodName) and finally a list of arguments (if any) enclosed in a pair of parentheses. It is to remember that the method called must belong to the class whose object has referred. We can also access fields of a class with a dot operator. Even when no argument( s) are required, a pair of parentheses is still necessary to distinguish member method call from the access of fields.

For example, The following statements declare the Rectangle object and access the length field of the firstRect object.

Rectangle.firstRect = new Rectangle();
firstRect.length = 5;

Similarly, the following statement uses the dot operator to invoke the setData () method of the firstRect object and pass the arguments 5 and 6 to 1 and b parameter of the method respectively.
firstRect.setData(5,6) ;

Now let us go through an example that demonstrates writing a class, creating objects (instances) of that class and using a dot operator to access fields and methods of the object. In this program, we create two classes: Rectangle class that we have discussed so far and RectangleArea class that instantiates and uses the Rectangle object. We should save this program with a file name which is the same as that of the class which contains the main() method. So we are saving it as (take care of case sensitivity).

Program to calculate the area of the rectangle using the concept of objects and class?

// Program to calculate the area of a rectangle using classes
class Rectangle {
   int length;
   int breadth;
   //method to initialize length and breadth of rectangle
      void setData(int l,int b) {
          length = l;
          breadth = b;
     //method to calculate area of rectangle
     int area () {
         int rectArea;
         rectArea = length * breadth;
         return rectArea;

     //class to create rectangle objects and calculate area
     class RectangleArea {
         public static void main(String[] args) {
            //Creating Objects
           Rectangle firstRect = new Rectangle() ;
           int result = firstRect.area();
           System.out.println("Area of rectangle ="+ result);


Output: When you compile this program, you find that two class files have created, one for Rectangle and one for RectangleArea. The Java compiler automatically puts each class into its own class file.
To run this program, you must execute the RectangleArea class. It is because the main () method is in this RectangleArea class and not in the Rectangle class. As a result, the following output displayed.
Area of rectangle = 30

Explanation: In the above program, we have declared two classes: Rectangle and RectangleArea. The Rectangle class contains two fields length and breadth of type int that correspond to the length and breadth of the rectangle respectively. Also, the Rectangle
class also contains two methods named setData() and area(). The method setData() initialises length and breadth fields of an object and area() calculates the area of the rectangle. This Rectangle class is different from all the classes. It does not have a main () method and therefore cannot run. It is merely a definition used to define and create Rectangle objects. So we define another class named RectangleArea that contains the main() method from where the program execution begins.

In the main (), the statement
Rectangle firstRect = new Rectangle();
creates a Rectangle object in memory and assign it to the reference variable firstRect
The statement,
firstRect.setData(5,6) ;

Invokes the method setData () on the object firstRect, and copies the arguments 5 and 6 to the parameters land b respectively. The flow of control is now within the body of the setData () method. Here, the values in land b are assigned to length and breadth instance variables respectively. After executing the body of the setData () method, the control now shifts back to the main () method and continues with the next statement,

int result = firstRect.area();
Here, the area () method is invoked on the firstRect object, causing the flow of control to jump to the area () method. In this method, we declare the variable rectArea which exist only within the body of the method. This variable created each time you the method is executed and destroyed when execution of method ends. All the variables you declare within the body of the method are local to the method and are only around while the method executed. These variables are known as local variables. In this variable, we store the area of the rectangle using the statement,
rectArea = length*breadth;
After this, the return statement reached, which in this example returns the value 30 and also causes the flow of control to jump back to the calling method, main(). The value is 30 is then substituted for the method name from where it called which then assigned to the variable result. This value is then displayed using the System.out.println() method.

multiple objects of the same class

You can create multiple objects of the same class. Each object has its copy of the fields of its class. If you make any changes in the fields of one object, then those changes do not affect the fields of other objects. So if you want to create two objects myRect1 and myRect2 of the Rectangle class, then you have to write,
myRect1.setData(5,6) ;
myRect2.setData(15,10) ;

Object instantiated from a class

Here each Rectangle object (i.e. myRect1 and myRect2) is unique and has its copy of the length and breadth fields. Changing length in the object myRect1 does not affect the value of length in the object myRect2. Since there is a unique copy of the field in each object (an instance of a class) so the fields also referred to as instance variables. Similarly, the methods area() and setData() are referred as instance method because you can only invoke in on the specific instance.
NOTE: Java allows multiple classes in a single java file as long as not more than one of the top level classes is declared public.

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.