Page 359 - Computer_Science_F5
P. 359
Computer Science (d) Types of constructors
In Java, there are two main types of constructors:
(i) Default constructor: Is a kind of constructor that has no arguments (empty
parentheses). It is used to give basic default values for the properties of a
FOR ONLINE READING ONLY
particular object. Java tends to create a default constructor automatically that is
not initialised if a constructor is not declared in your class. Program Example
5.20 demonstrates the default constructor.
Program Example 5.20:
Java program to create a class with default constructor
public class Car {
String color;
String make;
String model;
// Default constructor (no arguments)
public Car() {
color = “black”; // Default color
make = “unknown”;
model = “unknown”;
}
//other methods can be specified here
}
// Creating car objects using constructors
Car car1 = new Car(); // Uses default constructor
(ii) Parameterised constructor : This type of constructor enables you to specify
arguments within the parentheses during object creation. These arguments are
commonly utilised to initialise the object’s properties with values that you provide.
In a class, you can have multiple parameterized constructors, each accepting
different arguments to accommodate various initialisation scenarios. Program
Example 5.21 shows a sample parameterised constructor.
350
for Advanced Secondary Schools
Computer Science Form 5.indd 350 23/07/2024 12:34

