| |
|
1.12 Variables
Variables, whether local or global, can be declared and initialized in several ways:
- To declare:
int i;
- To declare and initialize:
int i = 10;
- To initialize after declaration:
i = 20;
- To declare multiple:
int i, j, k;
- To declare and initialize multiple:
int i = 0, j = 9, k = -2;
- To initialize multiple after declaration:
i = j = k = -1;
Like methods, variables can have specifiers to denote their access levels:
-
private int i;
-
int j;
-
protected int k;
-
public int l;
- The access level specifier is summarized in the following table:
| Specifier |
Class |
Package |
Subclass |
World |
|
| private |
Yes |
No |
No |
No |
This variable can only be read and modified from within the same class. If at all, the value is accessed by a method (e.g. getValue()) and modified through some other method that presumably involves checking the data. |
| no specifier (blank) |
Yes |
Yes |
No |
No |
This variable can additionally be read and modified by other classes in the package. |
| protected |
Yes |
Yes |
Yes |
No |
This variable can additionally be read and modified by classes that have been derived from this class. |
| public |
Yes |
Yes |
Yes |
Yes |
This variable can be read and modified by any class from anywhere. |
Local variables can be declared at any point, whether in the beginning of a method, or anywhere else. This is somewhat different from C, where variables must be declared at the beginning of a function.
public void computeSomething(int a) {
int i = 0; ... // lots of code ... String s = "This is towards the end"; ... ... }
|
Global variables must be declared within the class, but outside of any method:
public class MyClass {
int age; String firstName;
public MyClass {
... }
... }
|
|
|