Java Constructors:
- It is treated as a unique member characteristic because its name is similar to the class name.
- Java constructors are invoked while their objects are created.
- It is called such due to the fact, it constructs the value, i.e., offer information for the object, i.e., they may be used to initialize objects.
- Each class has a constructor when we don’t explicitly claim a constructor for any java class the compiler creates a default constructor for that class which does no longer have any return type.
- The constructor in Java can not be abstract, static, very last or synchronized and these modifiers aren’t allowed for the constructor.
Characteristics of Java Constructors:
- An interface can’t have the constructor.
- Constructors can’t be private.
- Abstract, static, final can’t be constructor .
- Constructors cannot return a value.
- Constructors does not have a return type; no longer even void.
- Constructors are routinely called while an object is created.
There are two types of constructors:
- Default constructor (no-arg constructor).
- Parameterized constructor.
Syntax:
1 2 3 4 5 | //Default constructor invoked Test c = new Test() //Parameterized constructor invoked Test c = new Test(name); |
1. Default constructor (no-arg constructor):
- A constructor does not have parameter’s is known as default constructor and no-arg constructor.
Example:
In this example, we are creating the no argument constructor in the Bike_Java class. It will be invoked at the time of object creation.
1 2 3 4 5 6 7 8 9 10 11 | package package_Java; class Bike_Java { Bike_Java() { System.out.println("Bike_Java is created"); } public static void main(String args[]) { Bike_Java b = new Bike_Java(); } } |
Output:
1 | Bike_Java is created |
2. Parameterized constructor:
- A constructor having an argument list with it’s data type is known as a parameterized constructor.
Example:
In this example, we are creating the constructor in the Dog_Java class and passing the arguments to the constructor.
1 2 3 4 5 6 7 8 9 10 11 12 | package package_Java; public class Dog_Java { String name; public Dog_Java(String name) { this.name = name; System.out.println(name); } public static void main(String[] args) { Dog_Java d = new Dog_Java("Simba"); } } |
Output :
1 | Simba |
Note: If there is no constructor defined in a class, then compiler automatically creates a default constructor.