我只是一個Java初學者。在做一些練習時,我遇到了一些困惑:我們可以在只有類引用的另一個類的構造函數中使用一個類的方法嗎?如果不是,爲什麼這樣呢?下面就讓我試着解釋:我們可以在其他類的構造函數中使用其他類的方法嗎?
public class MyCircle {
private int radius;
private Point centre;
public MyCircle(int x,int y,int r){
**centre.setX(x);**
**centre.setY(y);**
radius=r;
}
public MyCircle(Point p,int r){
centre=p;
radius=r;
}
public int getRaduis(){
return radius;
}
public void setRadius(int r){
radius=r;
}
public Point getCentre(){
return centre;
}
public void setCentre(Point p){
centre= p;
}
public int getCenterX(){
return centre.getX();
}
public int getCenterY(){
return centre.getY();
}
public void setCentreXY(int x,int y){
centre.setXY(x,y);
}
public double getArea(){
return Math.PI*radius*radius;
}
}
在第一構造centre.setX()
和center.setY()
顯示錯誤在編譯時,分別爲,如果我把center = new Point(x,y)
程序編譯容易。
另外方法center.setX()
和center.setY()
在setcenterXY()
不會產生任何問題。
是Point類:
public class Point {
private int x;
private int y;
public Point(){
x=8;
y=9;
}
public Point(int x,int y){
this.x=x;
this.y=y;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public void setX(int x){
this.x=x;
}
public void setY(int y){
this.y=y;
}
public void setXY(int x,int y){
this.x=x;
this.y=y;
}
public double distanceXY(int x,int y){
int diffX=this.x-x;
int diffY=this.y-y;
return Math.sqrt(diffX*diffX+diffY*diffY);
}
public double distanceXY(Point p){
int diffX=this.x-p.x;
int diffY=this.y-p.y;
return Math.sqrt(diffX*diffX+diffY*diffY);
}
}
'centre.setX()'如果你不初始化您所呼叫的'空.setX()' –
它不會編譯,因爲在構造函數中訪問它之前,您尚未初始化'center'。這就是爲什麼當你初始化它時,它編譯得很好。基本上只是'center.setX'在null上調用'setX',而'center = new Point(x,y)'將center的值設置爲null以外的值。 –
@OriLentz它會編譯好,它不會運行。 –