类的java静态初始化将打印构造函数中的内容
我的问题是为什么没有static的表不打印任何内容。但是用静电打印 我试着把它安装在main里面,然后打印出来。第一次打印staic对象时,由于共享静态属性,它还打印了bowl1、bowl2 第二个没有静态属性 是否有任何用例可供使用?以此为例:类的java静态初始化将打印构造函数中的内容,java,static,Java,Static,我的问题是为什么没有static的表不打印任何内容。但是用静电打印 我试着把它安装在main里面,然后打印出来。第一次打印staic对象时,由于共享静态属性,它还打印了bowl1、bowl2 第二个没有静态属性 是否有任何用例可供使用?以此为例: public class StaticInitialization{ //This without the static does not print anything static Table table =
public class StaticInitialization{
//This without the static does not print anything
static Table table = new Table();
public static void main(String[] args) { }
}
public class Table{
static Bowl bowl1 = new Bowl(1);
static Bowl bowl2 = new Bowl(2);
Table() {
System.out.println("Table()");
bowl2.f1(1);
}
}
public class Bowl{
Bowl(int marker) {
System.out.println("Bowl(" + marker + ")");
}
void f1(int marker) {
System.out.println("f1(" + marker + ")");
}
}
由于从未创建类StaticInitialization
的对象,因此变量table2
从未初始化,相应的newtable()
也从未执行
public class StaticInitialization{
// table1 is initialized when the class StaticInitialization is loaded
static Table table1 = new Table();
// table2 is initialized when a new instance of StaticInitialization is created
Table table2 = new Table();
...
}
如果删除static,则它将成为实例变量,只有在创建表的实例时才会初始化,这相当简单。如果
表
是静态初始化
的非静态
成员:
public class StaticInitialization{
/* Here static variable get initialized
when class is loaded and constructor of Table will get invoked */
static Table table = new Table();
public static void main(String[] args) { }
}
只有创建了StaticInitialization
的实例(即,new StaticInitialization()
在某处完成),它才会被初始化(即调用Table()
构造函数)
如果表
是静态
成员:
Table table = new Table();
它在加载
StaticInitialization
类时被初始化——这种情况经常发生,因为StaticInitialization
包含main
方法 这是它用静电打印的东西。静态表=新表();Bowl(1)Bowl(2)Table()f1(1),因为您从未在main()
中实例化任何内容。您在上面看到的有4行打印语句。所以它打印我的问题是,当我从表中删除static时,请参阅它不打印的代码中的注释。@EJP ok你是对的,我在main中尝试过。我需要实例化StaticInitialization,以便它实例化属性Duh。玩!谢谢,thsi现在已被理解。如果您有新问题,请发布新问题。更改原始问题会使现有答案无效。我将问题回滚到原始状态。对于这样的示例,是否有一些好的用例?我发现维护这样的代码有点困难。更常见的是将其与final一起使用来定义常量。通常,初始化没有副作用(如打印某些内容)。
static Table table = new Table();