2015-11-04 82 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; 
} 
相關問題