Java Constructor is a special method which can be invoked at the time of Object Creation. A constructor is used to initialize the newly created object.
For Example, We have a class called Hello when you create the object of the Hello Class
Hello Class Constructor gets Invoked like below
output
Example
Parameterized Constructor
For Example, We have a class called Hello when you create the object of the Hello Class
Hello Class Constructor gets Invoked like below
package com.practice; public class Hello { Hello() { /* Constructor */ System.out.println("Hello Class Constructor"); } public static void main(String[] args) { Hello hello = new Hello();//Object Creation } }
output
Hello Class ConstructorRules to declare a constructor
- A constructor must have the same name as Class.
- A constructor has no return type explicitly.
- A constrcutor can contain all Access Modifiers(private,default,protected,public).
- A constructor cannot contain Non-Access Modifiers(abstract,final,static,synchronized).
- A constructor can have parameters(arguments).
- A constructor can have throw clause i.e. constructor can throw an Exception.
- default Constructor (or) no-arg Constructor
- Parameterized Constructor
If the constructor doesn't contain any arguments(parameters) then such type of constructor is known as default constructor (or) no-arg Constructor. In any java class if we don't create any constructor manually compiler creates a one default constructor. If the programmer defines any constructor in java class java compiler will not create any default(no argument) Constructor. The default constructor gets invoked during The Object creation.
public class DefaultConstructorDemo { //default constructor declaration can be invoked during object creation public DefaultConstructorDemo() { System.out.println("default constructor...."); } public static void main(String[] args) { DefaultConstructorDemo d = new DefaultConstructorDemo(); } }
output
A Constructor with parameters(arguments) is called parameterized Constructor. A parameterized constructor is used to initialize the object. initializing the object means assigning values to object. This constructor is user-defined Constructor. Have a look at below example
Examplepublic class Account { private int accountId; private String name; /*parameterized constructor declaration used to initialize the instance variables.*/ public Account(int accountId, String name) { this.accountId = accountId; this.name = name; } public void printValues() { System.out.println("Account id is :"+accountId); System.out.println("name is :"+name); } public static void main(String[] args) { Account account = new Account(1, "bala"); account.printValues(); } }
output

