A class can contain any of the following variable types.
Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.They must be initialized explicitly before they are used.
void main()
{
int count;
//statement;
}
Example for local variables:
int counting(int n1,int n2)
{
int count;
count=n1+n2;
return(count);
}
2.Instance variables(Non-Static Field):
Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
Let’s look at syntax of instance variables:
class Taxes
{
int count;
/*...*/
}
{
int count;
/*...*/
}
Example for instance variables:
Class person
String name;
int age;
String gender;
};
person p1,p2,p3;
3.Class variables(Static Field)
:
Class variables are variables declared with in a class, outside any method, with the static keyword.If one object instance of that class changes the value of a class variable then all the other instances see the samelocal changed value.
Let’s look at syntax of class variables:
class Taxes
{static int count;
/*...*/
}
Example for class variables:
class person
{
String name;
int age;\
String gender;
static String city="Trivandrum";
};
person p1.p2,p3;
No comments :
Post a Comment