【问题标题】:Calling a constructor from a class in the main method?从主方法中的类调用构造函数?
【发布时间】:2016-02-05 11:32:37
【问题描述】:

我已经阅读了其他一些问题,但似乎仍然无法弄清楚如何让我的工作,感谢任何帮助。我到目前为止的代码如下。我希望能够调用一个 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;
    }
}

}

【问题讨论】:

  • 阅读更多关于 JAVA 类方面的“构造函数”,您将能够弄清楚。现在,您可以将方法 newPointParametersnewPoint 的名称更改为 Point。从方法签名中删除void并在main方法中添加Point p = new Point(42, 24)

标签: java class constructor main


【解决方案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】:

    应该是

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2013-08-27
        • 2016-05-31
        • 1970-01-01
        • 1970-01-01
        • 2013-08-10
        • 1970-01-01
        • 2018-09-25
        • 2011-03-05
        • 2013-05-08
        相关资源
        最近更新 更多