【第四課】面向對象編程---構造函數

/**************************************************
 * Time:2016年11月15日11:38:27
 * Purpose:構造函數
 * Author:ZJY
 * Summary:構造函數不屬於一般函數,會在類生成對象時被自動執行
 * KnowledgePoint:1.構造函數不能有返回值(void也不能有)
 		2.構造函數不需要調用但只會在類生成對象時被自動執行
 		3.java在構造一個類時,如果用戶沒有定義構造函數,則
 			會自動生成一個無參的構造函數; 但用戶如果定義了構造
 			函數則就不會自動生成構造函數
 		4.當創建類對象時,有且只有一個構造函數被調用(有參或者無參的)
***************************************************/

class A
{
	private int i;
	private int j;
	
	public void show()
	{
		System.out.printf("i = %d,j = %d", i,j);
	}
	public void set(int a, int b)
	{
		i = a;
		j = b;
	}
	
	public A()
	{
		
	}
	//構造函數:要求構造函數名要與類名相同;構造函數不能有返回值
	//構造函數不屬於一般的函數,它不需要被調用就會執行,
	//但只在創建類A的對象時被調用
	public A(int a, int b)
	{
		i = a;
		j = b;
		System.out.printf("無參構造函數被調用了!\n");
	}
}

public class TestConst_1
{
	public static void main(String[] args)
	{
		A aa = new A(6, 7);  //當new出類A的對象時會自動
						//把參數6,7發給類中的有參的構造函數(系統會自動識別有幾個參數)
		A aa = new A(); //會自動識別發送給無參的構造函數
		//aa.i = 1;
		//aa.j = 2;
		
		//aa.set(3, 4);
		
		aa.show();
		
		
		
	}
	
}

/**************************************************
 * Time:2016年11月15日13:10:56
 * Purpose:構造函數2
 * Author:ZJY
 * Summary:在java中當一個對象被創建時,會對類對象中的各個成員進行初始化
 * KnowledgePoint:
    1.如果是數值型的數據類型(int double float byte...)都會被賦值爲0
    2.如果是boolean型的數據會被賦值爲false
    3.如果是引用(引用實際就是受限指針)會被賦值爲null
    4.系統會先執行初始化時成員的初值,再執行構造函數中賦的值
    5.在java中所有的局部變量都要求手動初始化; 類屬性可以不初始化,
    	因爲它不屬於局部變量,類屬性會自動初始化
***************************************************/
class ConstFunction
{
	public int i; //i不是局部變量是一個類是屬性
	ConstFunction bb;
	public boolean flag;
	
	public ConstFunction(int i, boolean flag, ConstFunction bb)
	{
		this.i = i;
		this.flag = flag;
		this.bb = bb;
	}

	public ConstFunction()
	{

	}
	
	public void show()
	{
		System.out.printf("[show] i = %d\n", i);
		System.out.printf("flag = %b\n", flag); //boolean型輸出用%b或%B
		System.out.println("bb = " + bb + 'H'); 
		
	}
}

class TestConst_2
{
	public static void main(String[] args)
	{
		ConstFunction aa1 = new ConstFunction();

		aa1.show();  //ok
		
		ConstFunction aa2 = new ConstFunction(88, true, aa1);
		
		aa2.show();  //ok
		
		//int k;  //k是局部變量,如果沒有初始化是一個隨機值
		//在java中要求所有的局部變量都需要被初始化
		//System.out.printf("k = %d\n", k); //error
		
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章