Constructor Example Java Program
Definition
A constructor in a class is a special type of method called to create an object, It has the same name as that of the Class.
Constructor Types
- Default Constructor
- Parameterized Constructor
- Private(SingleTon) Constructor
Constructor Characteristics In Java
- A constructor has the same name of the Class
- A constructor has no explicit return type
- A constructor is called automatically, to create instance an object.
- A constructor must be the same as the name of the class.
- Not like methods, constructors are not members of a class. we cannot call directly
- A constructor can be overloaded.
- A Constructor with no argument is called default Constructor
- A Constructor with arguments is called Parameterized Constructor
- Private Constructor is used for Singleton Class
Syntax
NameOfClass() {
//Statements
}
Syntax Example
Class Constructor {
Constructor(){
System.out.print("Its Called");
}
}
Syntax Explanation
- In the example, the name of the constructor is the same as that of the class name. When the constructor is executed, "I am inside default constructor" will be printed.
Constructor Example Program
class Constructor {
Constructor() {
System.out.println("I am inside default constructor");
}
public static void main(String[] args) {
Constructor obj = new Constructor();
}
}
Sample Output
Output is:
I am inside default constructor
Basic Programs
- My First Example Java Program
- Constructor Example Java Program
- Parametrized Method Example Java Program
- Static Class and Its Usage in Java Example Program
- Static Function or Method and Its Usage in Java Example Program
- Default and Parameterized Constructor Java Example Program
- Constructor Chaining Java Example Program
- Singleton Class Using Private Constructor Java Example Program
- Constructor Overloading Example Java Program
- Simple Class and Array of Object Java Example Program
Read More Articles
- Multiple Inheritance Using Interface Example Java Program
- Single Inheritance Example Java Program
- Multilevel Inheritance Example Java Program
- Hierarchical Inheritance Example Java Program
- Find all Substrings of a given string Example Java Program
- Create Matrix Example Java Program
- Sum Of Three Numbers Example Java Program
- Heap Sort Example Java Program
- Twin Prime Example Java Program
- Compile Time Polymorphism Example Java Program