Constructor
is special type of method in java used to initialize the object. Constructor is
invoked at the time of object creation.
Rules For
Creating Java Constructor
Basically
two things keep in mind when we create constructor such as :
1) Constructor name
must be same as its class name
2) Constructor must have no explicit return type
Types OF
Constructor In Java
There are
two types of constructor in java such as:
1)
Default Constructor
2)
Parameterized Constructor
Default
Constructor In Java
A constructor
that have no parameter(argument) is known as default constructor.
Syntax Of
Default Constructor
class_name()
{
//
Code Of Block
}
Example Of
Default Constructor
class Hello
{
Hello() // Default Constructor
{
System.out.println(“Hello
World”);
}
Hello obj =
new Hello();
}
Output
Hello World
Parameterized
Constructor In Java
A
constructor that have parameters (arguments) is known as parameterized
constructor. It is used when we give different values to distinct object.
Syntax Of Parameterized
Constructor
class_name(parameter1,parameter2,……….)
{
//
Code Of Block
}
Example Of
Parameterized Constructor
class Emp
{
int empid;
String
name;
Emp(int I,String
n)
{
empid = I;
name = n;
}
void show()
{
System.out.println(empid+“
”+name);
}
public
static void main(String ar[])
{
Emp e = new
Emp(1,“john”);
Emp e1 = new Emp(2,”david”);
e.show();
e1.show();
}
}
Output
1 john
2 david
0 comments:
Post a Comment