Page 113 - ComputerScience_Class_11
P. 113
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.
5.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:
Program 1 Write a program to calculate the area and perimeter of a rectangle.
1 class rectangle
2 {
3 int length, breadth, area, perimeter; // Data members
4 void assign() // Method to assign values in length and breadth
5 {
6 length = 5;
7 breadth = 2;
8 }
9 void cal_area() // Method to calculate the area of the rectangle
10 {
11 area = length * breadth;
12 }
13 void cal_perimeter() // Method to calculate the perimeter of the rectangle
14 {
15 perimeter = 2*(length + breadth);
16 }
17 void display()
18 {
19 System.out.println("Area : " + area + " cm");
20 System.out.println("Perimeter : " +perimeter + " cm");
Objects 111

