簡體   English   中英

從main方法中的類調用構造函數?

[英]Calling a constructor from a class in the main method?

我已經閱讀了其他一些問題,但似乎仍然無法弄清楚如何使我的工作,任何幫助都值得贊賞。 我到目前為止的代碼如下。 我希望能夠調用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;
    }
}

}

它應該是

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

因此,當前,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);
}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM