Variable Declaration
|
x---------------------------- x------------------------------ x
| | |
Local Class-level Super class-level
| | |
local to a function instance variables instance variables
static variables static variables
private variables
Private variables
|
x-- direct reference
Instance variables
|
x-- direct reference
|
x-- instance reference
Static variables
|
x-- direct reference
|
x-- instance reference (conventionally discouraged)
|
x-- static reference
Note: Static variable declaration in the main() causes compilation error : illegal start of expression.
-
Local variable should not be static
-
The keywords that can come with an Outer class:
abstract final public
-
The keywords that can come with a Nested class:
static private protected public
-
The only modifier that can come with a local variable
final
-
Non-static nested class = Inner class
class VarDeclaration { public static void main(String[] args) { static int i = 0; OtherClass oc = new OtherClass(); oc.showX(); } } class SomeClass { int x = 10; //super class-level } class OtherClass extends SomeClass { int x = 20; //class-level void showX() { int x = 30; //local System.out.println("local x: " + x); System.out.println("class-level x: " + this.x); System.out.println("super class-level x: " + super.x); } }
-
Predefined reference variable refines the scope of the variables with same name declared in different levels.
-
Predefined reference should not be done in static context.