Constructors
About
Characteristics of a Constructor
Same Name as Class
class Person {
Person() { // Constructor name = Class name
System.out.println("Person object created!");
}
}No Return Type
class Example {
Example() { // Constructor
System.out.println("Object initialized!");
}
}Automatically Called
Can Have Parameters
Can Have Multiple Constructors (Constructor Overloading)
Can have access modifiers
Access Modifier
Description
Example
Types of Constructors in Java
1. Default Constructor (No-Argument Constructor)
2. Parameterized Constructor
Usage:
3. Copy Constructor
Usage:
4. Private Constructor
Usage:
5. Constructor Overloading
Usage:
Can we have Destructors in Java?
Why No Destructors in Java?
Alternatives to Destructors in Java
1. finalize() (Deprecated)
finalize() (Deprecated)2. try-with-resources (Preferred Approach)
try-with-resources (Preferred Approach)3. Explicit close() Method
close() MethodLast updated