Java Reference
In-Depth Information
Class variables
Variables in an object oriented programming can be of many types depending on where they
are declared. When a variable is declared inside a method then it is known as local variable.
When the variable is declared outside methods, then it is naturally declared inside a class.
These variables are known as class variables. Class variables behave differently than local
variables.
Let us declare some class variables:
Public class my_class {
public int a;
private int b;
Public void my_method()
{
}
}
In this example we have declared 2 class variables and one method in the class my_class.
Declaration of a class variable is done in the same way it is done for a local variable. You
define the modifier, the data type and finally the variable name.
When you declare your class variables as public then they are accessible from outside. They
are known as instance variables. It is because you can create many instances of the same
variable inside all the objects you create from the same class. Each instance of the same vari-
able can hold a different value. In case of private class variables, you can use them through
using get and set methods. We will see them in a section on encapsulation shortly.
There is one more type of variables which act more like constants. In Java programming
language they are known as static variables. Static variables are never instantiated. What it
means is that there is just one copy of this variable when you run your code. In contrast we
have seen instance variables where they have as many copies as there are objects. We will
see this topic in detail in objects section.
Search WWH ::




Custom Search