Search code examples
javaclassconstructorprogram-entry-point

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

}


Solution

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