一、 構造函數
/*
一個函數中定義的變量必須要初始化,否則編譯會報錯
一個類中的數據成員
1、 如果在定義的時候不初始化,則它的值是系統自動分配好的默認值! 如int型為零 boolean型是false
如本程序的A類對象就是這樣
2、 如果在定義的同時賦初值, 則是可以的,也就是說該值是生效的.注意在C++中則不可以,在C++中一個類的數據成員不能在定義的同時初始化,它只能在構造函數中初始化
如本程序的A類對象就是這樣
3、 如果在定義的同時賦初值,當然生效,但如果在構造函數中又改變了定義時賦的初值,
則該數據成員最終的值就是構造函數中修改之后的那個值,因為:
系統會先執行定義時賦的初值,然后再執行構造函數中賦的初值
如本程序的B類對象就是這樣
*/
class A
{
int i;
int j = 10;
boolean flag;
void show()
{
System.out.println("i = " + i);
System.out.println("j = " + j);
System.out.println("flag = " + flag);
}
}
class B
{
int i;
int j = 10;
boolean flag;
public B()
{
System.out.println("以前的值是 " + i + " " + j + " " + flag);
i = 88;
j = 88;
flag = true;
}
void show()
{
System.out.println("i = " + i);
System.out.println("j = " + j);
System.out.println("flag = " + flag);
}
}
class TestConst_3
{
public static void main(String[] args)
{
A aa1 = new A();
aa1.show();
B bb1 = new B();
bb1.show();
}
}
/*
在j2sdk1.4.2_16中的運行結果是:
--------------
i = 0
j = 10
flag = false
以前的值是 0 10 false
i = 88
j = 88
flag = true
--------------
*/
二、 this關鍵字
/*
關鍵字this:
1,在普通方法中,關鍵字this代表方法的調用者,即本次調用了該方法的對象
2,在構造方法中,關鍵字this代表了該方法本次運行所創建的那個新對象
*/
class A
{
private int i;
public A(int i)
{
this.i = i; //將形參 i 賦給該構造方法本次運行所創建的那個新對象的i數據成員
}
public void show(){
System.out.println("i = " + this.i);
//this表示當前時刻正在調用show方法的對象
//this可以省略
}
}
public class TestThis
{
public static void main(String[] args){
A aa1 = new A(100);
aa1.show();
A aa2 = new A(200);
aa2.show();
}
}
