class Programming {
// Constructor method
Programming() {
System.out.println("Constructor method called.");
}
public static void main(String[] args) {
Programming object = new Programming(); // Creating object
}
}
1. Class Declaration:
class Programming {
An empty class named Programming is declared.
2. Constructor Method:
Programming() {
System.out.println(“Constructor method called.”);
}
- Constructor: A constructor Programming() is declared. In Java, a constructor is a special method that gets executed automatically when an object of the class is created.
- The constructor in this program does not accept any parameters. This constructor, when invoked, prints the message “Constructor method called.” to the console.
3. Main Method (Program Execution Starts Here):
public static void main(String[] args) {
The entry point of the program which is executed when the program starts is the main method. Inside the main method, an object of the Programming class is created using the new Programming() statement:
- Programming object = new Programming();
- This statement calls the constructor Programming() to create the object, and the constructor will automatically be invoked.
- The constructor prints “Constructor method called.” to the console.
Step-by-Step Execution:
1. Program Execution Begins:
The main method is executed first.
2. Creating the Object:
- The declaration Programming object = new Programming(); instantiates an object of the Programming class.
- The expression new Programming() calls the constructor Programming().
- There is no code to show in this section.
3. Constructor Invocation:
The constructor outputs the string “Constructor method called.” to the screen.
4. Program Termination:
When the constructor finishes executing, so does the main method.
Output
Constructor method called.
Conclusion:
- Constructor: Constructor is a special type of method which is called automatically when an object of class is created.
- Flow of Execution: When the program creates the object of object type with new Programming() statement it calls constructor that print “Constructor method called.”
- Output: Program Print “Constructor method called.” to console.
- This is an example of constructors in Java.