简体   繁体   中英

Java constructor overloading bug?

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?

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

should just be this(0, 0, 0, 0);

this(new Line(0, 0, 0, 0)); means you are putting an argument that is a new Object of Line class with its parameterized constructor.

this(0, 0, 0, 0); means that you are only putting values in the constructor which this prefers to, in your code, your this represents the class Line . So this should work, not the first you did.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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