Employee Emp = new Employee()
// new Employee() => will trigger the constructor call
class Employee{
Employee() {}
}
Key Feature of a constructor:
Purpose of consturcotr:
Every time we are creating an object : we are sort of reusing the code to initialize something
Types of constructor
Non parameterized constructor
Parameterized constructor
Copy constructor
class Account{
name, balance;
Account(name, balance)
{
this.name = name;
this.balance = balance;
}
Account (Account account) {
Account(Account.getName(), Account.getBalance());
}
getName()
{...}
getBalance()
{...}
main()
{
Account obj1 = new Account("Raj", 1000);
Account obj2 = new Account(obj1); // this will put value from obj1
}
Can a constructor call another constructor?
Yes We can call it. (Like in the example of copy constructor we just saw)
Can a constructor be overloaded?
Yes. ( same constructor name, accepting: different number of parameters.. and different types of parameters)
Note that whenever a constructor is called : it is stored in heap memory
Whenever the reference to the heap memory is gone:
the garbage collector clears that heap mamory
( this is not there in c++;
we would need the keyword delete for that.)