Page 132 - CTS - CSA TP - Volume 2
P. 132
COMPUTER SOFTWARE APPLICATION - CITS
TASK 2: Details of Persons
class Person {
String name;
int age;
// Default constructor
Person() {
this(“Unknown”, 0); // Call parameterized constructor with default values
}
// Parameterized constructor with name
Person(String name) {
this(name, 0); // Call parameterized constructor with default age
}
// Parameterized constructor with name and age
Person(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println(“Name: “ + name);
System.out.println(“Age: “ + age);
}
}
public class PersonDemo {
public static void main(String[] args) {
// Creating instances of Person with different constructors
Person person1 = new Person();
Person person2 = new Person(“John”);
Person person3 = new Person(“Alice”, 25);
// Displaying details of persons
System.out.println(“Details of person1:”);
person1.display();
System.out.println(“\nDetails of person2:”);
person2.display();
System.out.println(“\nDetails of person3:”);
person3.display();
}
}
117
CITS : IT & ITES - Computer Software Application - Exercise 97