1、構造函數
用來new 對象,一旦自定義後系統不在幫你自動創建。只能和類名一樣,不要void等修飾。
public class pp{
int ii;
int mm;
//構造函數
pp(int _ii,int _mm){
ii = _ii;
mm = 100;
}
public static void main(String[] args) {
pp ipp = new pp(1,2);
//pp ppp = new pp(); //這樣會報錯,因爲已經自定義了構造函數,只用按照構造參數new對象
System.out.println("ipp.ii = " + String.valueOf(ipp.ii));
System.out.println("ipp.mm = " + String.valueOf(ipp.mm));
}
}
2、練習 寫一個小程序,要求如圖1-1 所示
代碼:
class ZPoint{
int x;
int y;
int z;
public String js(){
int temp;
temp = 0;
temp = x*x + y*y + z*z;
return String.valueOf(temp);
}
public void setX(int _x){
x = _x;
}
public void setY(int _y){
y = _y;
}
public void setZ(int _z){
z = _z;
}
}
public class TestPoint {
public static void main(String[] args) {
ZPoint a = new ZPoint();
a.setX(1);
a.setY(2);
a.setZ(3);
System.out.println("距離0點有:" + a.js());
}
}