繁体   English   中英

在构造函数中创建对象与在声明中创建对象之间的区别

[英]Difference between creating object in the constructor and creating object in declaration

这两个代码段有什么区别

第一

import javax.swing.*;

public class Mainframe extends JFrame {

    private JLabel nameLbl = new JLabel( "Name" );
    private JTextField nameTf = new JTextField( "10" );

}

第二

import javax.swing.*;

public class Mainframe extends JFrame {

    private JLabel nameLbl;
    private JTextField nameTf;

    public Mainframe() {
        nameLbl = new JLabel( "Name" );
        nameTf = new JTextField( "10" );
    }

}

在您的特定情况下没有太大区别。

但是通常,如果要使用一些自定义值初始化对象,则可以在构造函数中进行。

例如:

public Mainframe(String name, String number) {
    nameLbl = new JLabel( name );
    nameTf = new JTextField( number );
}

在构造函数和声明中创建任何变量的对象都是类似的

请参阅以下示例:

public class DemoClass {

  String str;
  String newStr = new String("I am initialized outside");

  public DemoClass() {

    System.out.println(newStr);
    str = new String("I am initialized inside");
    System.out.println(this.str+"\n");

  }

 public static void main(String[] args) throws Exception {

    DemoClass dc = new DemoClass();

  }
}

在上面的示例中,您可以看到-在构造函数中,变量正在初始化,因为在调用构造函数之前,JVM已在内存中创建了DemoClass的对象。

构造函数仅用于初始化任何实例变量。

创建对象的流程:在创建DemoClass 对象之前,JVM将创建从属对象,即首先创建newStr ,然后再创建DemoClass对象。

就功能而言,没有。 但是,如果在第二种情况下有多个构造函数,并且通过非默认构造函数创建Object,则实例变量将保持为null。

在内部,实例变量声明和您的构造函数代码在字节码中变得相同。即使初始化程序块也按以下顺序合并:

1)Instance member declaration
2)All initializer block declarations in the order of their occurence
3)Constructor code

编译后,字节码将其视为一个

编译器将对象字段的显式初始化复制到每个构造函数(非参数构造函数或参数构造函数)中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM