Constructor
- Constructor is a special,method which is used to initialize the object at the time of creation.
- Constructor is a member function of class and initializes objects of a class.
Characteristics of constructor
- Constructor does not have return type,not even void.
- In constructor the method name is same as the class name.
- Constructor can be overloaded.
- Constructor can invoke automatically.
Types of constructor
1.Default Constructor:-
- If no constructor are defined for a class,the compiler automatically generate default constructor.
- Default constructor don't have parameters.
2. Parameterized Constructor:-
- If any constructor which have parameters then it is called parameterized constructor.
- Constructor is also overloaded (java allows overloading of constructor as well as methods).
//Syntax for Default and Parameterized constructor
public DemoConstructor
{
int num1=45; // Defining Default Constructor
int num2=65;
}
public DemoConstructor(int x,int y)↑・Ҝ.↑↑↑
{
num1=x; //Defining Parameterized Constructor
num2=y;
}
DemoConstructor dc=new DemoConstructor(); //Default Constructor Object Creation
DemoConstructor dc1=new DemoConstructor(20,30); //Parameterized Constructor Object Creation
No comments:
Post a Comment