英文:
Can we access the static member of a class without initializing obects?
问题
public class Test{
static Another a; // 不初始化也可以访问Another类的静态成员
public static void main(String[] args){
System.out.println(a.i);
}
}
class Another{
public static int i=20;
}
这里我可以在不初始化对象的情况下访问类Another的静态成员,系统显示的输出结果是20。
public class Test{
public static void main(String[] args){
Another a; // 但是当我在main方法内部声明时,系统会抛出错误
System.out.println(a.i);
}
}
class Another{
public static int i=20;
}
Test.java:5: error: variable a might not have been initialized
System.out.println(a.i);
^
但是当我将声明移到main代码块内部时,系统会报错。为什么会这样呢?
英文:
public class Test{
static Another a;// without initializing i can able to access static member of Another class
public static void main(String[] args){
System.out.println(a.i);
}
}
class Another{
public static int i=20;
}
Here I can able to the access the static member of class Another without initializing the object and the system is displaying the output as 20.
public class Test{
public static void main(String[] args){
Another a;// but when i declare this inside the main method system is throwing error
System.out.println(a.i);
}
}
class Another{
public static int i=20;
}
Test.java:5: error: variable a might not have been initialized
System.out.println(a.i);
^
But when i move the declaration inside main block system throws an error. why is that?
答案1
得分: 1
以下是翻译好的部分:
public static void main(String[] args){
Another i
System.out.println(a.i);
}
可以替换为
public static void main(String[] args){
System.out.println(Another.i);
}
您之所以出现 **错误** 并不是因为静态变量 `i`,而是因为局部方法变量 `Another a` 没有被初始化 **,由于您没有初始化变量a,函数内部的局部变量在读取其值之前必须被初始化。
英文:
public static void main(String[] args){
Another i
System.out.println(a.i);
}
this can be replaced with
public static void main(String[] args){
System.out.println(Another.i);
}
You are getting error not because the static variable i
but **because of local method variable Another a
is not initialized ** , Since you have not initialized a, the local variable inside a function must be intialized befor reading its value.
答案2
得分: 0
你应该使用Another.i
来访问static
变量i
,而不是a.i
。
如果a
有值,a.i
是有效的语法,但这会令人困惑(因为任何阅读你代码的人可能错误地认为i
是实例变量)。如果在访问时a
未初始化,编译器是不允许的。
这两个代码片段的区别在于这里(当a
是一个static
变量):
static Another a;
a
有一个默认值null
。
而在这里(当a
是一个局部变量):
Another a;
它没有默认值。
英文:
You should access the static
variable i
with Another.i
, not a.i
.
a.i
is valid syntax if a
has a value, but it's confusing (since anyone who reads you code may falsely assume i
is an instance variable). And if a
is not initialized when you access it, the compiler doesn't allow it.
The difference between the two snippets is that here (when a
is a static
variable):
static Another a;
a
has a default value of null
.
While here (when a
is a local variable):
Another a;
it has no default value.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论