这个point board=new point[10]是point的新示例吗?

kkbh8khc  于 2021-06-29  发布在  Java
关注(0)|答案(2)|浏览(423)

我做了这个练习,他们问我创建了多少个point示例,他们回答了14,但我数了13,因为我不把板算为示例。它是?为什么?因为对我来说,我们创建了一个新的电路板,有10个点的大小,但我们没有示例,因为我们需要一个x和一个y来做不?

public class Point {

    private double x, y;

    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public Point addition(Point p) {
        return new Point(x + p.x, y + p.y);
    }

    public String toString() {
        return "Point [x=" + x + " , y=" + y + "]";
    }
}

public class Test {

    public static void main(String[] args) {
        Point p = new Point(1, 1);
        Point[] board = new Point[10];

        for (int i = 0; i < 6; i++)
            tab[i] = p.addition(new Point(i, 1));

        System.out.println(p);
        Point p2 = p;
        p2 = p.addition(tab[0]);
        System.out.println(p + " " + p2);
    }
}
yws3nbqq

yws3nbqq1#

请看下面的代码,它是创建14次。我添加了一个静态方法和静态对象来计算对象的数量。此外,您可以将调试点放在构造函数中,并检查自己,它是如何被调用的。

public class Point
{

    private double x, y;
    private static int objectCount;//Counter to keep track of objects

    public  static int getObjectCount()
    {
        return objectCount;
    }
    public Point(double x, double y)
    {
        this.x = x;
        this.y = y;
        objectCount++;
    }

    public Point addition(Point p)
    {
        return new Point (x + p.x, y + p.y );
    }

    public String toString()
    {
        return "Point [x=" + x + " , y=" + y + "]";
    }
}

测试类被更改为在不同阶段打印此计数

public class Test
{
    public static void main(String[] args)
    {
        Point p = new Point(1, 1);
        System.out.println("No of Objects created after new Point(1, 1) = " + Point.getObjectCount());
        Point[] board = new Point[10];
        for (int i = 0; i < 6; i++)
            board[i] = p.addition(new Point(i, 1));
        System.out.println("No of Objects created after  for loop  = " + Point.getObjectCount());
        System.out.println(p);
        Point p2 = p;
        p2 = p.addition(board[0]);
        System.out.println("No of Objects created after  p.addition(board[0]) = " + Point.getObjectCount());
        System.out.println(p + " " + p2);
    }
}

o/p是

No of Objects created after new Point(1, 1) = 1
No of Objects created after  for loop  = 13
Point [x=1.0 , y=1.0]
No of Objects created after  p.addition(board[0]) = 14
Point [x=1.0 , y=1.0] Point [x=2.0 , y=3.0]
lnxxn5zx

lnxxn5zx2#

是的,你的逻辑是正确的。创造 board (数组) Point )不涉及创建任何 Point 示例。它只是一个数组。
但是有14个例子 Point 在代码中创建:
第3行创建( new Point (1 ,1) )
其中六个在for循环中创建,另外六个在 addition 方法调用。
9号线一个 addition 方法)。
我想你错过了最后一个:)

相关问题