Home:ALL Converter>Java constructor overloading bug?

Java constructor overloading bug?

Ask Time:2016-12-01T10:58:43         Author:ItzikH

Json Formatter

i'm practicing java and trying to learn if this is a bug or on purpose: i stumble into something i don't really understand while trying to learn about the difference between shallow copy and hard copy + static class members + overloading constructors + using this in the constructor I've made this code over mesh things together and somethings don't add up:

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);
    }
} 

Problem is : when I call the count Line numbers on the next line
System.out.println("totalLines in app: " + line.count);
I get back 3 Line counts instead of only 2. Because I'm learning java right now, I run the debugger on intelliJ and apparently there is a double call for Line constructor with no arguments on
Line line = new Line();
this constructor seems to runs twice there is a double take on the line
this(new Line(0, 0, 0, 0));
and I'm breaking my head over it. can someone explain to me whats happening here? Maybe overloading constructors isn't that healthy after all, and if you don't know how to implement it right your overloading unnecessary objects and garbage?

Author:ItzikH,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/40901903/java-constructor-overloading-bug
Scary Wombat :

\nline = new Line(100, 100, 200, 200);\nthis(new Line(0, 0, 0, 0));\nthis(new Line(0, 0, 0, 0));\n\n\nshould just be this(0, 0, 0, 0);",
2016-12-01T03:03:01
yy