Java Constructors

Java Constructors
A constructor is a special member method which will be called by the JVM implicitly(automatically) for
placing user/programmer defined values instead of placing default values.
Constructors are meant for initializing the object. Constructor is a special type of method that is used
to initialize the state of an object.
Constructor is invoked at the time of object creation. It constructs the values i.e. data for the object
that is why it is known as constructor.
Constructor is just like the instance method but it does not have any explicit return type.
Advantages of Constructors:
1. A constructor eliminates placing the default values.
2. A constructor eliminates callling the normal method implicitly.
RULES/CHARACTERISTICS of a Constructor:
1. Constructor name must be same as its class name.
2. Constructor should not return any value even void also.
3. Costructors should not be static .
4. Constructors should not be private.
5. Constructors will not be inherited at all.
6. Constructors are called automatically whenever an object is cereating.
Types of Constructors:
There are two types of constructors:-
1. Default constructor (no-argument constructor)
2. Parameterized constructor
1. Default constructor (no-argument constructor):- A constructor is one which will not take any
parameter.A constructor that have no parameter is known as default constructor.
Syntax:-
class < class name >
{
classname() //default constructor
{
Block of statements;
...................;
}
..................;
};
Example:-
//Start Of TestConstructor
class TestConstrucutor
{
int a, b;
TestConstructor()
{
System.out.println(" Default Constructor !!!");
a = 10;
b = 20;
System.out.println("Value of a = " +a);
System.out.println("Value of b = " +b);
}
};
class MainConstructor
{
public static void main(String args[])
{
TestConstructor obj = new TestConstructor();

}
};
2. Parameterized Constructor:- A constructor is one which takes some parameters.
Syntax:-
class < class name >
{
classname(list of parameters) //paramiterized constructor
{
Block of statements;
...................;
}
..................;
};
Example:-
//Start Of TestConstructor
class TestConstrucutor
{
int a, b;
TestConstructor(int x, int y)
{
System.out.println(" Parameterized Constructor !!!");
a = x;
b = y;
System.out.println("Value of a = " +a);
System.out.println("Value of b = " +b);
}
};
class MainConstructor
{
public static void main(String args[])
{
TestConstructor obj = new TestConstructor(10,20);
}
};

No comments:

Post a Comment