Java4teachus

Thursday, April 04, 2019

Parameterized Constructor in Java

Parameterized Constructor 

The Purpose of parameterized constructor to create multiple objects with respect to same class for planing different values .



Definition
A Constructor is said to be parameterized if and only if it always takes parameters .

Syntax 
class <classname>
{
----------------
<ClassName>(Parameterized Constructor)
{
Block Of Statements's;

}


Q. Java program which illustrate the concept of parameterized Constructor .

Program :-

Class Test

{
int a,b
Test (int x,int y)
{
System.out.println("Test - parameterized constructor);
a=x;
b=y;
System.out.println("val of a="+a);
System.out.println("val of b="+b);
}
}//Test
Class Test Demo
{
Public static void main(String args [])
{
Test  t1= new Test (1,2);
Test  t2= new Test (10,20);
Test  t3= new Test (100,200);
}
}


Rule:2 
When we create an object with parameterized constructor then it is mandatory  to the java program to defined parameterized constructor (other was compile time error) .

Rule:3 
When we create an object with default & parameterized constructor then it is mandatory  to the java programmer to defined both default parameterized constructor .

Note
constructor are meant for initializing the data member of current class . If we dont initil- sum of the data member of 3rd class in the current class constructor then those uninitialized data member initial by default constructor of super class of current class . i.e(java.lang.object).

Over Loaded Constructors

A Constructor is said to be over loaded if and if constructor name is name but its signature is different signature represents the following points .

a) No.of parameters                   

b) Types of parameters
c) Order of parameters

Here we consider the following over loaded constructor call method.

Test  t1= new Test (10,20);
Test  t2= new Test (100);
Test  t3= new Test (1.5f ,2.5f);
Test  t4= new Test (10,1.5f);
Test  t5= new Test (1.5f,10);

Here Test(......)are called over loaded constructor. 

No comments:

Post a Comment

Thanks for visiting my site..