实例初始化器和构造函数之间有什么区别? [英] What's the difference between an instance initializer and a constructor?

查看:117
本文介绍了实例初始化器和构造函数之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道编译代码的原因是这样的:

Just wondering about the reason of compiling code like this:

class MyClass extends AnotherClass {
  {
    MySecondClass object = new MySecondClass();
    object.doSomething();
  }
}

这段代码和构造函数中的代码有什么区别?此代码在>对象创建之前执行

Whats the difference between this code and code in constructor? This code executes before the object creation.

推荐答案

没有名称的大括号内的代码将是类的构造函数的一部分,并在类构造函数中包含的逻辑之前执行。

The code inside the braces with no names will be part of the constructor of the class and be executed before the logic contained in the class constructor.

快速示例:

public class Foo {
    {
        System.out.println("Before Foo()");
    }

    public Foo() {
        System.out.println("Inside Foo()");
    }

    {
        System.out.println("Not After Foo()");
    }
}

这篇关于实例初始化器和构造函数之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆