从main方法中的类调用构造函数?

时间:2015-11-04 19:57:05

标签: java class constructor main

我已经阅读了其他一些问题,但似乎仍无法弄清楚如何让我的工作,任何帮助表示赞赏。我到目前为止的代码如下。我希望能够调用newPointParameters来创建一个新类。

public class Lab4ex1 {
public static void main(String[] args) {
    System.out.println("" + 100);

    new newPointParameter(42,24);
}
class Point {
    private double x = 1;
    private double y = 1;

    public double getx() {
        return x;
    }
    public double gety() {
        return y;
    }
    public void changePoint(double newx, double newy) {
        x = newx;
        y = newy;
    }
    public void newPointParameters(double x1, double y1) {
        this.x = x1; 
        this.y = y1;
    }
    public void newPoint() {
        this.x = 10;
        this.y = 10;
    }
    public double distanceFrom(double x2, double y2) {
        double x3 = x2 - this.x;
        double y3 = y2 - this.y; 
        double sqaureadd = (y3 * y3) + (x3 * x3);
        double distance = Math.sqrt(sqaureadd);
        return distance;
    }
}

}

3 个答案:

答案 0 :(得分:1)

应该是

public static void main(String[] args) {
    System.out.println("" + 100);
    Point p = new Point();
    p.newPointParameter(42,24);
}

答案 1 :(得分:1)

因此,目前,newPointParameters和newPoint都不是构造函数。相反,它们只是方法。要使它们成为构造函数,它们需要与构造类

共享相同的名称
class Point {

  private double x = 1;
  private double y = 1;

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

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

然后,当您想要创建新点时,您只需执行以下操作

对于默认点

public class Lab4ex1 {

  public static void main(String[] args) {
    System.out.println("" + 100);

    //this will create a new Point object, and call the Point() constructor
    Point point = new Point();
}

对于带参数的点

public class Lab4ex1 {

  public static void main(String[] args) {
    System.out.println("" + 100);

    //this will create a new Point object, and call the 
    //Point(double x, double y) constructor
    Point point = new Point(10.0, 10.0);
}

答案 2 :(得分:0)

newPointParameters不是构造函数。我认为这就是你要做的事情:

public Point(double x1, double y1) {
    x = x1;
    y = y1;
}

然后,您可以使用此构造函数在主类中创建一个Point对象:

Point p = new Point(42, 24);

看起来你也希望newPoint()成为一个构造函数,所以看起来应该是这样的:

public Point() {
    x = 10;
    y = 10;
}