一直在书上看的静态变量用类名直接调用就可以了。偶然发现new了个实例也是可以操作的。
下面的代码在eclipse里调试通过,虽然有小贴士“the static field should be accessed in a static way”,
但可以通过,可以运行。和个朋友讨论了下,他在.net下用C#编译通不过。就糊涂了。
难道java让静态变量可以用实例调用了,那这样static就没啥意思了啊
public class Animal {
static int weight = 30;
}
class Inter {
public static void main(String[] args) {
Animal an = new Animal();
Animal.weight = 4;
an.weight = 8;
System.out.println(Animal.weight);
}
}
下面的代码在eclipse里调试通过,虽然有小贴士“the static field should be accessed in a static way”,
但可以通过,可以运行。和个朋友讨论了下,他在.net下用C#编译通不过。就糊涂了。
难道java让静态变量可以用实例调用了,那这样static就没啥意思了啊
public class Animal {
static int weight = 30;
}
class Inter {
public static void main(String[] args) {
Animal an = new Animal();
Animal.weight = 4;
an.weight = 8;
System.out.println(Animal.weight);
}
}
但是这样不是更好吗,
如果java没有这个功能的话,java对象需要使用getclass(),然后强转在调用,多麻烦。
Net还有静态类,静态构造器,代理
net把我搞得更加糊涂!
static int weight = 30;
}public class Inter{
public static void main(String[] args) {
Int an = new Int();
Int.weight = 4;
an.weight = 8;
System.out.println(Int.weight);
}
}你刚才的代码就没法运行,主函数应该写在公共类里,静态的变量是在类加在的时候加载的
非static可以调static,static不能调非static
而C#就只能用类名调用了