Page 90 - computer science (868) class 11
P. 90
Generally, to declare a class, the following components are required:
1. Access Specifier
2. “Class” keyword
3. Class name
4. Data members
5. Methods
The data members and methods are encapsulated in curly brackets.
4.2.1 Creating an Object of a Class
Instance of a class is also called an object and the process of creating an object of a class is called instantiation.
The syntax for creating an object:
[class name] [space] [object name] = new [space] [constructor];
For example:
book computer = new book();
A constructor is a function or method that has the same name as the class and is used for initialising an object created
by the class “book”. You will learn more about constructors later in this book.
Let’s see an example:
class rectangle
{
int length, breadth, area, perimeter; // Data members
void assign() // Method to assign values in length and breadth
{
length = 5;
breadth = 2;
}
void cal_area() // Method to calculate the area of the rectangle
{
area = length * breadth;
}
void cal_perimeter() // Method to calculate the perimeter of the rectangle
{
perimeter = 2*(length + breadth);
}
void display()
{
System.out.println("Area : " + area + " cm");
System.out.println("Perimeter : " +perimeter + " cm");
}
public static void main()
{
rectangle obj = new rectangle();
obj.assign();
obj.cal_area();
obj.cal_perimeter();
obj.display();
}
}
What does the above code mean?
1. In the above program, an object is being created. The name of the object is “obj”. The line that is used to create the
object is “rectangle obj = new rectangle();”.
8888 Touchpad Computer Science-XI

