简体   繁体   中英

Calling a constructor from a class in the main method?

I've read some of the other questions, but still couldn't seem to figure out how to get mine to work, any help is appreciated. The code I have so far is given below. I want to be able to call a newPointParameters to create a new class.

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

}

It should be

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

So, currently, neither newPointParameters nor newPoint are constructors. Rather, they are just methods. To make them into constructors, they need to share the same name as the class the construct

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

Then, when you want to create a new point, you simply do the following

For a default 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() constructor
    Point point = new Point();
}

For the Point with parameters

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 is not a constructor. I think this is what you are looking to do:

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

Then you can create a Point object in your main class using this constructor:

Point p = new Point(42, 24);

It looks like you also intended for newPoint() to be a constructor, so it should look like this:

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

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