Thursday, 30 April 2015

Tutorial On Constructor In Java

First we need to understand why we need constructor in our programs.It will be bad approach to initialize variable in class each time instance is created than it would be more easy to have initialization done at the time of object creation java allow to do this using a constructor.

CONSTRUCTOR:

A constructor initialize an object immediately upon creation.The name of constructor should be same to class which it resides.Constructor don't have return type,not even void.It is used to initialize instance variable as you can see in this program that we use constructor to initialize current and resistor value and the name of constructor is same as class name.Declaration of constructor looks like declaration of method except constructor uses same name as a class and have no return type.we can not write more than one one constructor of a same class having same number and type of argument.

CODING:

class current
{
double current;
double resistance;
//This is a constructor for current class
current ()
{
current = 3;
resistance = 100;
}

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

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

OUTPUT:

voltage is=300volt
voltage is=300volt







No comments:

Post a Comment