我知道静态块在main之前运行。 但是,正常的块也运行之前主或主后?静态块和普通块
class prog
{
static
{
System.out.println("Static");
}
{
System.out.println("Block");
}
public static void main(String args[])
{
prog obj=new prog();
System.out.println("Main");
}
}
我知道静态块在main之前运行。 但是,正常的块也运行之前主或主后?静态块和普通块
class prog
{
static
{
System.out.println("Static");
}
{
System.out.println("Block");
}
public static void main(String args[])
{
prog obj=new prog();
System.out.println("Main");
}
}
静态块在加载类时执行,其中当创建包含该块的类的实例时执行常规块。
只是在java 7以前的记录静态块被执行之前,在项目中搜索main()方法。但是从java 7 main()首先查找。所以你会得到一个错误,如果你没有main.So I know the static blocks run before main
有点含糊不清。在执行静态块之前查找main()方法,但主要执行将在处理静态块之后开始。
在调用相应的构造函数之前,还会执行非静态块。 例如
public class Tester {
{
System.out.println("In some random block");
}
static {
System.out.println("In static block");
}
public Tester() {
System.out.println("Constructor");
}
public static void main(String args[]) {
Tester t = new Tester();
}
}
将打印时一个类的实例被实例化
In static block
In some random block
Constructor
非静态块一个,只要你实例化一个对象,你的情况inside main
运行。尝试之前打印的东西prog obj=new prog();
如果我有像下面这样的东西,它会在main之前运行。
class prog {
static {
System.out.println("Static");
}
{
System.out.println("Block");
}
prog obj = new prog();
public static void main(String args[]) {
System.out.println("Main");
}
}
*每当您实例化包含这些块的类的对象*时,就会运行非静态块。 –
另外值得一提的是,在执行类构造函数之前,类中的* non-'static * *块将被执行**。请参阅http://stackoverflow.com/a/17001104/1065197 –
是的,非静态块是由编译器为所有类生成的'init'方法的一部分,并且该方法在构造函数之前运行。 – Claudiu
其实静态块或SIB(静态初始化块),在加载类加载的时间,因此之前的主()..
执行,但同样是没有非静态的情况下块或IIB(实例初始化块),它只是在创建对象(实例)的加载时间,正如其名字也阐明了同样...
我觉得你有我的观点......
静态块是块,如果我们指定任何变量或类静态我们可以acc通过类名将其数据成员放入另一个类或该类之外。 Normal Block是创建类或创建该类的对象的块。如果我们想在另一个类中使用它,我们必须创建该类的构造函数,然后才能访问它的对象。 所以这是静态块和普通块的主要差别块
当编译时创建该类的实例时,将运行普通块。静态块在程序执行中只会运行一次。所以如果你想在创建该类的实例之前打印一些东西,然后将其放在静态块中。
正常初始化块被运行。像main一样,静态方法不需要实例,所以这两个东西是不相关的。
你为什么不跑来看看自己? – SudoRahul
说真的,在fav IDE中运行此代码会更容易。如果您手头没有,请使用http://ideone.com –
更具体地说,静态块在类被加载时运行......哪一个是在main之前。 –