實體化方式(new):
1.記憶體分配
2.屬性隱含預設初始化
3.屬性明顯初始化
4.執行建構子
5.分配物件記憶體位置
所以說,一new之後建構子就被執行了
建構子是跟class同名的方法,不用return,預設無參數(但是可以給)
package tw.xxx.myfirstproject.oop;
public class TestConstructorEx1 {
public TestConstructorEx1(String name){
//我是不能自己取名的建構子,一定得跟class同名,一new就出場
System.out.println("run here."+name);
}
public void play(){
System.out.println("play ball");
}
public static void main(String[] args) {
TestConstructorEx1 test1 = new TestConstructorEx1("mary");
test1.play();
new TestConstructorEx1("john").play();
//以上這種不寫test1的用法亦可,可以參照下面的1+1,此為anonymous object匿名物件
//但這樣若是需要使用多次則每次都要重建物件,效率較低,浪費資源
System.out.println("完");
int a=1;
a=a+1;
System.out.println("a="+a);
System.out.println("1+1="+(1+1));//類似匿名物件,不用幫1取名叫a
}
}
run here.mary
play ball
run here.john
play ball
完
a=2
1+1=2
package tw.xxx.myfirstproject.oop;
public class TestThisEx1 {
// 下面這兩個是實體變數
public String name = "janet";
public int age = 22;
public TestThisEx1() {
// 我是沒有參數的建構子
this(28);
// this其實就等於類別的("不是"方法的)TestThisEx1
// 呼叫這個class本身,而且是有參數的,所以會呼叫到有參數的建構子
// 注意他會先呼叫有參數的建構子,然後才列印下面的文字,所以會是先有second再有first
System.out.println("first constructor");
}
public TestThisEx1(int age) {
this.age = age;
System.out.println("second constructor" + " and age=" + age);
}
public void setInfo(String name, int age) {// 左邊這兩個是區域變數
this.name = name;
this.age = age;
// 這邊的this.name跟this.age都是指class的變數(實體變數),用以跟區域變數做區別
}
public void showInfo() {
System.out.println(name);
System.out.println(age);
System.out.println("結束");
}
public static void main(String[] args) {
TestThisEx1 test1 = new TestThisEx1();
test1.setInfo("judy", 18);
test1.showInfo();
}
}
second constructor and age=28
first constructor
judy
18
結束