Java 在另一个内部调用构造函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18935559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:39:33  来源:igfitidea点击:

Java calling constructor within another

javaobjectconstructor

提问by Anshin

could someone help me with calling the first constructor and putting it in the second and third? I may have some problems with the syntax, it seems...

有人可以帮我调用第一个构造函数并将其放在第二个和第三个中吗?我的语法可能有一些问题,似乎......

http://pastebin.com/5x11Mkyy

http://pastebin.com/5x11Mkyy

采纳答案by DaoWen

Your linked example is really long and I'm getting confused by all the non-English comments, so I'll just give you a short example. If you want to call another constructor within a constructor, you just use the thiskeyword. Here's a sample class that uses thisto delegate the work of the "default" (no-arg) constructor to a 1-arg constructor:

你链接的例子真的很长,我对所有非英语评论感到困惑,所以我只给你一个简短的例子。如果要在构造函数中调用另一个构造函数,只需使用this关键字。这是一个示例类,用于this将“默认”(无参数)构造函数的工作委托给 1-arg 构造函数:

public class MyClass {

  public final int X;

  public MyClass() {
    this(1); // Use X=1 by default
  }

  public MyClass(int x) {
    X = x;
  }

}

This technique is covered in Using the thisKeyword: Using thiswith a Constructorin Oracle's Java Tutorials.

在 Oracle 的 Java 教程中使用this关键字:this与构造函数一起使用中介绍了此技术。