Java 构造函数重载错误?

Java constructor overloading bug?

我正在练习 java 并尝试了解这是错误还是故意的: 在尝试了解浅拷贝和硬拷贝 + 静态 class 成员 + 重载构造函数 + 在构造函数中使用 this 之间的区别时,我偶然发现了一些我不太了解的东西我已经制作了这段代码将事物网格化在一起,但有些事物不会加起来:

package com.example.java;

import java.awt.*;

public class Test {

    Line line;

    public Test() {
        line = new Line(100, 100, 200, 200);
        line.draw();
    }

    public static void main(String[] args) {
        Test shapes = new Test();
        Line line = new Line();
        System.out.println("totalLines in app: " + line.count);
    }
}

class Line {

    private Point p1, p2;
    static int count = 0;

    Line(){
        this(new Line(0, 0, 0, 0));
    }

    Line(int x1, int y1, int x2, int y2) {
        p1 = new Point(x1, y1);
        p2 = new Point(x2, y2);
        count++;
    }

    Line(Line l1) {
        p1 = l1.p1;
        p2 = l1.p2;
        count++;
    }

    void draw() {
        System.out.println("Line p1= " + p1 + "\t,p2= " + p2);
    }
} 

问题是:当我在下一行调用计数行号时
System.out.println("totalLines in app: " + line.count);
我得到 3 行计数,而不是只有 2 行。 因为我现在正在学习 java,所以我 运行 intelliJ 上的调试器,显然在
上有一个没有参数的 Line 构造函数的双重调用 Line line = new Line();
这个构造函数好像是运行s 两次有一个double take就行了
this(new Line(0, 0, 0, 0));
我为此伤透了脑筋。有人可以向我解释这里发生了什么吗? 也许重载构造函数毕竟不是那么健康,如果你不知道如何正确地实现它,你就会重载不必要的对象和垃圾?

  1. line = new Line(100, 100, 200, 200);
  2. 这(新行(0, 0, 0, 0));
  3. this(新行(0, 0, 0, 0));

应该只是this(0, 0, 0, 0);

this(new Line(0, 0, 0, 0)); 表示您要放置的参数是 Line class 的新对象及其参数化构造函数。

this(0, 0, 0, 0); 意味着您只将值放入 this 更喜欢的构造函数中,在您的代码中,您的 this 代表 class Line.所以这应该有用,而不是你第一次做的。