Practical-18
Write a java program which implements the Default Constructors.
Introdution
A default constructor is a special type of constructor in Java which is used to initialize the class attributes to the default values. Default constructors are automatically generated by the compiler if no other constructors are defined in the class. The purpose of a default constructor is to improve code readability, as it can be used to set a known, standard state for all class objects.
Code
class Constructors {
// Constructor with no parameters
Constructors() {
System.out.println("This is the default constructor");
}
// Driver code
public static void main (String args[]) {
Constructors c1 = new Constructors();
}
}
Output
This is the default constructor
Explanation
The code above creates a Constructors class and defines a constructor with no parameters. The constructor just prints a message which indicates that the constructor was called. Finally, the main() method creates an instance of the Constructors class, which in turn calls the constructor and prints the message.