Constructor
Constructor
===========
A constructor is a special member function that is used to initialize a newly created object and is
called just after the memory is allocated for the object. It can be used to initialize the objects at the time
of object creation.
Syntax:
=======
class classname
classname(Arguments)
statements;
....
Rules :
5) It can be overloaded.
Ex:
class myclass
myclass ()
System.out.println("Welcome to constructor");
myclass m1,m2,m3;
Note :
If there is no constructor in our class, then the system will generate the default constructor for the class
with no arguments and no statements.
Parameterized Constructor :
-------------------------------------
Ex:
class car
{
String cname,comp; //member variable
float price;
int model;
cname=cn;
comp = co;
model =m;
price=p;
void display()
car c1,c2,c3;
c1.display();
c2= new car("Tavera","Cheverlet",2022,80000);
c2.display();
c3.display();
Ex: 2
-----
class bank
String cus_name;
int acno;
float amount;
cus_name = cname;
acno = ano;
amount = amt;
}
b1.display();
b2.display();
Constructor Overloading :
----------------------------------
A class can have multiple constructor with different number of arguments or different types of
arguments.
Ex:
class product
int qty;
string pname;
float price;
product()
qty = 10;
price = 250;
product(string pn, int q, float p) // arguments (or) parameters -> local variables
pname = pn;
qty = q;
price = p;
product(string pn)
{
pname = pn;
qty = 0;
price = 0;
void display()
p1.display();
p2.display();
p3.display();