Constructors in Java
A constructor is a special method in Java that is used to initialize objects. It is called automatically when an object of a class is created. Constructors have the same name as the class and do not have a return type. They can be used to set initial values for object attributes or perform any other necessary initialization tasks.
Types of Constructors
Constructor Type | Description | Example |
---|---|---|
Default Constructor | Constructor with no parameters. | public MyClass() {} |
Parameterized Constructor | Constructor with parameters. | public MyClass(int x, String y) {} |
Copy Constructor | Constructor that creates an object by copying the values from another object of the same class. | public MyClass(MyClass obj) {} |
Private Constructor | Constructor that is marked as private and used for preventing the instantiation of a class. | private MyClass() {} |
Static Constructor | Constructor that is used to initialize static variables or perform other static initialization tasks. | static { /* static initialization code */ } |
Examples
Here are five examples demonstrating the use of constructors in Java:
-
Default Constructor
public class Person { private String name; public Person() { name = "Unknown"; } }
-
Parameterized Constructor
public class Car { private String brand; private int year; public Car(String brand, int year) { this.brand = brand; this.year = year; } }
-
Copy Constructor
public class Point { private int x; private int y; public Point(Point other) { this.x = other.x; this.y = other.y; } }
-
Private Constructor
public class Singleton { private static Singleton instance; private Singleton() { // Private constructor to prevent instantiation } public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
-
Static Constructor
public class MathUtils { private static final double PI; static { PI = 3.14159; } }
Tags
Core Java tutorials