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
0 comments:
Post a Comment