Sunday, 3 May 2015

Filled Under:

Tutorial On Parametrized Constructor In Java

As in our previous Tutorial on constructor in java example we can see that all the objects we have create have same value of resistance and current that is not use full because we need to initialize all variables with different values to do this we can use parametrized constructor this make much more useful.for example we have create parametrize constructor for current class that will initialize current and resistor values in current class one thing should be noted that values should be given to parametrized constructor at the time of object creation.One Should be kept in mind that we cannot use reserved keyword as a parameter name.

DATA TYPES:

Any type of data can be used as a parameter in constructor  such as integer,double and float.Array and object can also be used as a parameter as shown in below.
current( current[])

CODING:

class current
{
double current;
double resistance;
//Creating Parameterize constructor
current (double c,double r)
{
current = c;
resistance = r;
}

double volt() 
{
return current*resistance;
}
}

class voltage
{
public static void main(String args[])
{
//Creating Object Of current class
current cur=new current(10,40);
current cur1=new current(30,10);
System.out.println("Voltage is = "+cur.volt()+" volt");
System.out.println("Voltage is = "+cur1.volt()+" volt");
}
}  

OUTPUT:

voltage is =400volt
voltage is=300volt





0 comments:

Post a Comment