Page 124 - CTS - CSA TP - Volume 2
P. 124
COMPUTER SOFTWARE APPLICATION - CITS
EXERCISE 97 : Use constructors in JAVA
Objectives
At the end of this exercise you shall be able to
• know about constructors and its function in JAVA
• develop Java programs using different constructors such as default and parameterised constructors
• develop Java programs using Constructor chaining.
Requirements
Tools/Materials
• PC/Laptop with Windows OS
• JDK Software
• Text Editor (Visual Studio/Sublime/Notepad)
Procedure
Constructors in Java can have various forms, including default constructors, parameterized constructors, and
constructor chaining. Here are examples demonstrating the use of various constructors in Java:
1 Default Constructor:
TASK 1: Area of Rectangle
// Area of Rectangle using default constructor
class Rectangle {
double length;
double width;
// Default constructor
Rectangle() {
length = 0;
width = 0;
}
// Method to calculate the area of the rectangle
double calculateArea() {
return length * width;
}
}
public class Rectangle_Demo {
public static void main(String[] args) {
// Creating an instance of Rectangle using the default constructor
Rectangle rectangle = new Rectangle();
// Displaying the area of the rectangle
109