DEV Community

Karthick M
Karthick M

Posted on

Constructor

  • Constructor name should be the class name.
  • Constructor is a special method used to initialize the value for instance variable when the object created.
  • when we create an object contructor will automatically run.
  • we cannot manually run/call the contructor.
  • this is the java keyword.

Costructor types:
1.Default constructor
2.No-Argument Constructor
3.Parameterized constructor

Example:
class Bank {

int accountNo;
String name;
int balance;

Bank(int accountNo, String name , int balance)
{
    this.accountNo = accountNo;
    this.name = name;
    this.balance = balance;
}

public static void main(String[] args)
{

    Bank accholder = new Bank(101,"kumar",1000);
    System.out.println(accholder.accountNo);//101

    Bank accholder1 = new Bank(102,"hari",1000);
    System.out.println(accholder1.accountNo); //102

}
Enter fullscreen mode Exit fullscreen mode

}

  • What is the purpose of constructor?
    Used to initial the values for instance variables at the object creation. By using *this * keyword, we can access/assign values to the instance varaiable inside constructor. this refers to current object only. So this keyword is used to differentiate instance variables from local variables.

  • what is constructor over loading?
    while we are creating more than one contructor, arguments will differ for each contructors.
    example:
    public class Payilagam {

    String name;
    String email;
    String password;

    Payilagam(String name, String email, String password)
    {
    this.name = name;
    this.email = email;
    this.password = password;
    }

    Payilagam( String email, String password)
    {

    this.email = email;
    this.password = password;
    

    }

    public static void main(String[] args)
    {
    Payilagam user1 = new Payilagam("kumar","abc.com","kumar@123");
    System.out.println(user1);

    Payilagam user2 = new Payilagam("abc.com","kumar@123");
    System.out.println(user2);
    

    }

}

Top comments (0)