2015-11-04 86 views
0

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

}

+0

在JAVA方面了解更多关于 “构造”类,你将能够弄清楚。现在你可以将'newPointParameters'和'newPoint'方法的名字改为'Point'。从方法签名中删除'void'并在'main'方法中添加'Point p = new Point(42,24)' – 2015-11-04 20:05:44

回答

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

应该

public static void main(String[] args) { 
    System.out.println("" + 100); 
    Point p = new Point(); 
    p.newPointParameter(42,24); 
} 
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; 
} 
相关问题