`

声明前为什么能赋值却不能输出,都是使用

阅读更多
public class Stack {
	static {
		a = 6;// ---- 1
		System.out.println(a);// ---- 2
	}
	static double a = 3.234; 

	public static void main(String[] args) {
		System.out.println(a);
	}

	public void go() {
		a = 7;
		System.out.println(a);
		int a;
	}
}
 

以上代码1处可以,2处却编译出错

 

回答:

就是说,成员在使用前(此“前” 指 代码书写文本顺序)需定义,且成员必须是类或接口C的实例或静态变量,(局部变量不受文本顺序限制)


* The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer of C.
使用须出现在C的实例变量初始化体或静态变量初始化体,C的实例初始化块或静态初始化块中       

* The usage is not on the left hand side of an assignment.
使用须在赋值式左手边(这里原文表达可能有些问题,通过后文确认了)

* The usage is via a simple name.
使用须是简单命名

* C is the innermost class or interface enclosing the usage.
C是包含该“使用”的直接上层类或接口

 

摘自:

http://java.sun.com/docs/books/jls/third_edition/html/classes.html#287406

8.3.2.3 Restrictions on the use of Fields during Initialization

 

 

public class Test  {

    public int instancevariable;

    public static int staticvariable;

    static {
        System.out.println("Static Initializer...");
    }

    {
        System.out.println("Instance Initializer...");
    }

    public Test() {
        System.out.println("Constructor...");
    }
}

 

class UseBeforeDeclaration {
	static {
		x = 100; // ok - assignment
		int y = x + 1; // error - read before declaration
		int v = x = 3; // ok - x at left hand side of assignment
		int z = UseBeforeDeclaration.x * 2;
		// ok - not accessed via simple name
		Object o = new Object() {
			void foo() {
				x++;
			} // ok - occurs in a different class

			{
				x++;
			} // ok - occurs in a different class
		};
	}
	{
		j = 200; // ok - assignment
		j = j + 1; // error - right hand side reads before declaration
		int k = j = j + 1;
		int n = j = 300; // ok - j at left hand side of assignment
		int h = j++; // error - read before declaration
		int l = this.j * 3; // ok - not accessed via simple name
		Object o = new Object() {
			void foo() {
				j++;
			} // ok - occurs in a different class

			{
				j = j + 1;
			} // ok - occurs in a different class
		};
	}
	int w = x = 3; // ok - x at left hand side of assignment
	int p = x; // ok - instance initializers may access static fields
	static int u = (new Object() {
		int bar() {
			return x;
		}
	}).bar();
	// ok - occurs in a different class
	static int x;
	int m = j = 4; // ok - j at left hand side of assignment
	int o = (new Object() {
		int bar() {
			return j;
		}
	}).bar();
	// ok - occurs in a different class
	int j;
}
 
分享到:
评论
1 楼 iamzhoug37 2015-02-28  
您能说一下"局部变量不受文本顺序限制" 是什么意思吗? 不是很明白

相关推荐

Global site tag (gtag.js) - Google Analytics