比如这个例子:
public class Static
{
static{
int z =1;
}
public static void main(String args[])
{
System.out.println(z);//1
Static s = new Static();
System.out.println(s.z);//2
}
}
1和2都编译不过,提示“ cannot resolve symbol”
那我想问的是:
静态初始化块里定义的变量能用在哪里?如上例所示,它既不能当作静态变量来访问,也不能当作类的成员变量来访问。怎么访问z?
public class Static
{
static{
int z =1;
}
public static void main(String args[])
{
System.out.println(z);//1
Static s = new Static();
System.out.println(s.z);//2
}
}
1和2都编译不过,提示“ cannot resolve symbol”
那我想问的是:
静态初始化块里定义的变量能用在哪里?如上例所示,它既不能当作静态变量来访问,也不能当作类的成员变量来访问。怎么访问z?
如果你想维Static类设置一个静态的变量z,应该这样做:
public class Static
{
int z;
static{
z =1;
}
……
或者直接:
public class Static
{
public static int z =1;
……
当然,后面的简单方式只能用于初始化过程不复杂,仅仅是设置几个值的情形。
int z;
static{
z =1;
}
就相当于static int z=1;
静态初始化块是在类变量之前初始化的,你们写的例子也不自己试一下就贴出来,不怕误了别人" non-static variable z cannot be referenced from a static context"但如果写成
static int z;
static{
z =1;
}
又没意义了。希望高手指点
怎么没意义了?
//一堆静态变量
int a;
int b;
...........
}
相当于
static int a;
static int b;
-------------------------------------------------------------------------
您好,网美书店全场5折-8.8折,深圳东莞所有地区送书上门(免配送费),书到付款!网美书店网址:http://www.wanme.com咨询QQ: 419777139
static{
int z =1;
}
public static void main(String args[]){
System.out.println(z);//1
Static s = new Static();
System.out.println(s.z);//2
}
}
----
1处错误:cannot resolve symbol
因为你的z出了作用域,这里作用域只是static块。当然会报错;
-
2处错误:cannot resolve symbol
同上;
---------
下面是一个可能的修改方案:
public class Static{
public static int z;
static{
z =1;
}
public static void main(String args[]){
System.out.println(z);//1
Static s = new Static();
System.out.println(s.z);//2
}
}
-------
下面说下static块的作用
设立这样的语法只是为了方便静态变量的初始化(可参见TIJ),这样做的好处是
便于维护代码而已。
{
static int i;
static
{
i=100;
}
public static void main(String[] args)
{
System.out.println(TestStatic.i);
}
}
{
public static void main(String[] args)
{
//fill the staff array with three Employee objects;
Employee[] staff = new Employee[3];
staff[0] = new Employee("Harry", 40000);
staff[1] = new Employee(60000);
staff[2] = new Employee();
for(int i = 0; i < staff.length; i++)
{
Employee e = staff[i];
System.out.println("name = " + e.getName()
+ " id = " + e.getId()
+ " salary = " + e.getSalary());
}
}
}
class Employee
{
private String name = "";
private double salary;
private int id;
private static int nextId;
//object initialization block;
{
id = nextId;
nextId++;
}
public Employee(String n, double s)
{
name = n;
salary = s;
}
public Employee(double s)
{
//this 的一种用法,放在第一行掉用另一个构造函数;
this("Employee #" + nextId, s);
}
//缺省构造函数;
public Employee()
{
//name initialized to "";
//salary not explicitly set --initialized to 0;
//id initialized in initialization block;
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public int getId()
{
return id;
}
}