You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中通过this关键字实现构造器间调用的技术咨询

Constructor Chaining with this() in Java (Explained with Your Thinking in Java Example)

Let’s walk through exactly how constructor chaining works using that Flower class snippet from Bruce Eckel’s book—this is a classic example of how to avoid code duplication and keep your constructor logic clean.

First, the Core Concept: this() for Constructor Calls

In Java, you can call one constructor of a class from another using this(...). This is called constructor chaining, and it’s super useful for reusing code across multiple constructors instead of copying the same logic over and over.

Breaking Down the Flower Class Code

Let’s go through each constructor step by step to see the chain in action:

1. The No-Arg Constructor (Flower())

Flower() {
    this(47, "hi"); // Calls the Flower(int, String) constructor
    System.out.println("Default constructor");
}
  • The first line this(47, "hi") tells Java: "Before running any code in this constructor, execute the constructor that takes an int and a String."
  • Rule to remember: this() must always be the first statement in a constructor—Java enforces this to ensure initialization happens in a predictable order.

2. The Two-Parameter Constructor (Flower(int petalCount, String s))

Flower(int petalCount, String s) {
    this(petalCount); // Calls the Flower(int) constructor
    this.s = s;
    System.out.println("Int and String args");
}
  • Again, the first line is a this() call—this time it invokes the single int parameter constructor. This lets us reuse the code that initializes petalCount instead of writing this.petalCount = petalCount here too.
  • After the chained constructor finishes, this constructor sets the s member variable and prints its message.

3. The Single Int Constructor (Flower(int petalCount))

Flower(int petalCount) {
    this.petalCount = petalCount;
    System.out.println("Constructor with int arg only; petalCount = " + petalCount);
}
  • This constructor doesn’t call any other constructors (it’s the "base" of this chain). It uses this.petalCount to distinguish the class member variable from the method parameter (since they have the same name)—that’s a different use of this (referencing the current object), not constructor chaining.

4. The Single String Constructor (Flower(String s))

Flower(String s) {
    System.out.println("Constructor with String arg only; s = " + s);
    this.s = s;
}
  • This is another standalone constructor—no chaining here. It just prints a message and sets the s member variable (again using this to avoid name collision).

What Happens When You Create a new Flower()?

Let’s trace the execution flow for the no-arg constructor call:

  1. new Flower() triggers Flower()
  2. Flower() calls Flower(47, "hi")
  3. Flower(47, "hi") calls Flower(47)
  4. Flower(47) runs its code: sets petalCount to 47 and prints its message
  5. Control returns to Flower(47, "hi"): sets s to "hi" and prints its message
  6. Control returns to Flower(): prints "Default constructor"

So the output you’d see is:

Constructor with int arg only; petalCount = 47
Int and String args
Default constructor

Key Rules for Constructor Chaining with this()

  • Must be first: this() has to be the very first line in your constructor—you can’t put any other code before it.
  • No cycles: You can’t have a chain that loops (e.g., Flower() calls Flower(int) which calls Flower()). Java will throw a compile error if you try this.
  • Match parameters: The arguments you pass to this() have to exactly match the parameter list of another constructor in the same class.

Why Use This?

The biggest benefit is code reuse. If multiple constructors need to do the same initialization (like setting petalCount), you can put that logic in one constructor and have others call it. This makes your code easier to maintain—if you need to change how petalCount is initialized, you only have to update one place instead of every constructor that touches it.

内容的提问来源于stack exchange,提问作者Fish_In_A_Suit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:16:38