Skip to content

Chapter 2 : Classes, Objects and Methods

Saket Khopkar edited this page Jan 4, 2022 · 6 revisions

What is a Class?

  • Class contains variables (data members) and functions (member functions / methods).
  • A class is a template for an object, and an object is an instance of a class.
  • Class is a collection of objects of similar types.
  • Class is a user defined data type.
  • Syntax:
class ClassName {
datatype instance-variable1; datatype instance-variable2;
:
datatype instance-variableN;
return_datatype methodName1(parameter-list)
{
// body of method
}
return_datatype methodName2(parameter-list)
{
// body of method
}
:
return_datatype methodNameN(parameter-list)
{
// body of method
} }

Description of Syntax:

  • Class is defined using class keyword. ClassName is any valid java identifiers.
  • Data or variables defined within a class are called instance variables because each instance of the class (that is, each object of the class) contains its own copy of these variables. Thus, the data for one object is separate and unique from the data for another. The variables and functions defined inside the class are called members of the class.
  • Class declaration only creates a template; it does not create an actual object.
  • Class body written inside curly braces { and }. It does not terminate with semicolon.
import java.lang.*;
class Rectangle
{
    int len, bre;
    void getData(int l, int b)
    {
        len = l;
        bre = b;
    }
    void putData()
    {
         System.out.print(“Area = “ + len*bre);
    }
}
classRectArea
{
    public static void main(String args[ ])
    {
        Rectangle r = new Rectangle();
        r.getData(20,15);
        r.putData();
    }
}
// Output: Area = 300

What is an Object?

  • Object is an instance of a class. Creating an object is called as instantiating an object.

  • An object is a block of memory that contains space to store instance variables and methods.

  • Once the class is defined we can create any number of objects of that class.

  • Objects are created by using new operator (dynamic memory allocation operator).

  • Steps for Creating Object: Creating objects of a class is a two-step process.

  • Step 1: Declare a variable of the class type. This variable does not define an object. Instead, it is simply a variable that can refer to an object.

  • Syntax: ClassName reference_variable;

  • Example: Rectangle r; // declare reference to object.

  • After this line executes r contains the value null, which indicates that it does not yet point to an actual object. Any attempt to use object rat this point will result in a compile-time error.

  • Step 2: Acquire an actual, physical copy of the object and assign it to that variable. We can do this using the new operator. The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns a reference to it. This reference is the address of memory of the object allocated by new. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated.

  • Syntax: reference_variable = new ClassName();

  • Here, reference_variable is a variable (object) of the class type being created. The ClassName is the name of the class that is being instantiated. The class name followed by parentheses specifies the constructor for the class.

  • Example: r = new Rectangle(); // allocate a Rectangle object

  • Above line allocates an actual object and assigns a reference of it to r. After this line executes, we can user as a Rectangle object. But in reality, r simply holds the memory address of the actual Rectangle object. The effect of these two steps of code is shown in Figure.

  • Above both statements can be combined into a single statement as follows:

  • ClassName object_name = new ClassName();

  • Rectangle r = new Rectangle();

  • Here Rectangle() is default constructor.

Assigning Object Reference Variables:

  • One object reference can be assigned to another object reference variable, then the copy of the object is not created but copy of the reference is made.
Rectangle r1 = new Rectangle();
Rectangle r2 = r1;
  • Here,r1 and r2 refer to same objects and no separate copy will be created. It simply makes r2 refer to the same object as r1.
  • Thus, any changes made to the object through r2 will affect the object to which r1 is referring, since they are the same object.
  • Although r1 and r2 both refer to the same object, they are not linked in any other way. For example, a subsequent assignment to r1 will simply unhook r1 from the original object without affecting the object or affecting r2.
  • For example:
Rectangle r1 = new Rectangle ();
Rectangle r2 = r1;
// ...
r1 = null;

Here, r1 has been set to null, but r2 still points to the original object.

Creating / Defining Methods:

  • Classes consist of two things: instance variables and methods. Syntax:
return_type function_name (parameter_list)
{
// body of method
}
  • Example:
void calculate(int l, int b)
{
len = l;
bre = b;
System.out.print(“Area = “ + len*bre);
}
  • Here, return_type specifies the type of data returned by the method. This can be any valid type, including class type. If the method does not return a value, its return type must be void.
  • Methods that have a return type other than void return a value to the calling routine using the following form of the return statement: return value;
  • The function_name of the method is any legal identifier other than those already used by other items within the current scope.
  • The parameter_list is a sequence of type and identifier pairs separated by commas. If the method has no parameters, then the parameter list will be empty.

Declaring Instance Variable:

  • Data or variables defined within a class are called instance variables because each instance of the class (that is, each object of the class) contains its own copy of these variables.
  • Thus, the data for one object is separate and unique from the data for another.
  • Syntax : datatype instance-variable1, instance-variable2, instance-variableN;
  • Example : int a, b, c;

Accessing Class Members:

  • Object contains data members (instance variables) and member functions (methods). Each object has its own memory space for data members.
  • Object name and dot (.) operator is used to access variables and methods from outside the class.
  • Variables and methods can be access directly from within the class.
  • Syntax: object_name . Variable_name = value;
  • Object_name . method_name(parameter_list);
  • Example: r1.len = 20; r2.len = 10; r1.bre = 15; r2.bre = 8; r1.calculate (20, 15); r2.calculate (10, 8);

Array of Objects:

  • Array of object is the collection of objects of the same class.
  • The given syntax will define an array of reference, therefore assign object to individual reference in the array to declare the array of object.
  • Method 1: ClassName array_name[]; array_name = new ClassName[size];
  • Method 2: ClassName array_name[ ] = new ClassName[size]; Here, array_name is the array of object.
  • Example:
Student s[];
s = new Student[5];
Or 
Student s[ ] = new Student[5];
  • It will create array of 5 objects of student class.
  • We need to use constructor in order to construct array of objects as follows:
for(int i=0;i<=4;i++)
{
s[i] = new Student();
}
// Program to accept & display data of five students.
import java.io.*;
class Student
{
    String name;
    int rollno;
    float per;
    InputStreamReaderisr=new InputStreamReader(System.in);
    BufferedReader br=new BufferedReader(isr);
    void getData()
    {
        try
        {
            System.out.println("Input student details: ");
            name=br.readLine();
            rollno=Integer.parseInt(br.readLine());
            per=Float.parseFloat(br.readLine());
        }
        catch(Exception e)
        {
            System.out.println("Exception Occurred: “ + e);
        }
    }
    void putData()
    {
        System.out.println("Name = " + name);
        System.out.println("Roll No = " + rollno);
        System.out.println("Percentage = " + per);
    }
}
class Program1
{
    public static void main(String args[])
    {
        Student s[] = new Student[5];
        int i;
        for(i=0;i<=4;i++)
            s[i] = new Student();
        for(i=0;i<=4;i++)
            s[i].getData();
        for(i=0;i<=4;i++)
            s[i].putData();
    }
}