Tuesday, 28 April 2015

Initialization Of Instance Variable Using Object In Java

In this tutorial I have  created two classes current and voltage class.current class is  used for  declaring variables and I have created object named cur each time object is created it contain its own copies of instance variable in this example current and resitance  are instance variable .The dot between object name and instance variable creates link between variable of other class then I assign a value to instance variables.

DIFFERENCE BETWEEN INSTANCE AND CLASS VARIABLE:

Class variable and instance  variable are  declared with in a class but not in constructor or in method.Class variable have only one copy for each class while instance variable have different copies for each object generally class variables are used when we need to declare some constant while instance variable is used when values is not constant.Instance variable is created when object is created while a class variable is created when program is started.

CODING:

class current
{
double current;
double resistance;
}
class voltage
{
public static void main(String args[])
{
//Creating Object Of current 
classcurrent cur=new current();
//assiging value of current and resistance in instance variablecur.current=3;
cur.resistance=100;
double vol = cur.resistance * cur.current;
 System.out.println(vol);
}

}  


OUTPUT:


No comments:

Post a Comment