標籤:需求 tag 樣本 name work soft 調用 test 自身
1.構造方法
什麼是構造方法?
構造方法是一種特殊的方法,方法名必須與類名完全相同,沒有任何傳回型別,連void也沒有。
構造方法有什麼作用?
構造方法用於對類的成員變數進行初始化。
樣本:
class MyDate{ //Field int year; int month; int day; //Constructor MyDate(){} //沒有參數的構造方法 MyDate(int _year, int _month, int _day){ //有參數的構造方法 year = _year; month = _month; day = _day; } }
public class Test01{ public static void main(String[] args){ //建立對象 MyDate date = new MyDate(2017,10,29); //調用的是有參數的構造方法 System.out.println(date.year + "年" + date.month + "月" + date.day + "日"); } }
2.this關鍵字
什麼是this關鍵字?
this關鍵字是一個參考型別,在堆中每一個JAVA對象都有this,this儲存的是記憶體位址,這個記憶體位址指向這個對象自身。
this關鍵字可以用在哪些地方?
this可以用在成員方法中。
this可以用在構造方法中。
樣本:
this 用在成員方法中。
class Employee{ //Field int empNum; String empName; //Constructor Employee(){} Employee(int num, String name){ empNum = num; empName = name; } //Method //成員方法 public void work(){ System.out.println(empName + " is working!"); //成員方法中訪問成員變數必須加上"引用." //this 指的是當前的對象,誰去訪問這個成員方法,this就代表誰 //如果使用的是同一個類中的變數,那麼可以省略"引用." System.out.println(this.empName + " is working!"); } public void m1(){ this.m2(); m2(); } public void m2(){ System.out.println("Testing!"); } }
public class Test02{ public static void main(String[] args){ //建立對象 Employee e1 = new Employee(01,"Loafer"); e1.work(); //建立對象 Employee e2 = new Employee(02,"Sorcerer"); e2.work();
e2.m1(); } }
this 還可以用來區分成員變數和局部變數,當成員變數和局部變數重名的時候可以用this來區分。
class Animal{ //Field private int age; //Method //成員方法 public void setAge(int age){ this.age = age; //this.age 表示的是 屬性裡面的age, 而"="後面的age表示的是方法裡面的變數age } //成員方法 public int getAge(){ return age; } }
this 用在構造方法中,通過一個構造方法去調用另一個構造方法,目的是為了實現代碼的重用。
class MyDate { //Field int year; int month; int day; //Constructor //需求:預設日期是2017年10月28日 MyDate(int year, int month, int day){ this.year = year ; this.month = month; this.day = day; } MyDate(){ this(2017,10,28); /* this.year = 2017; this.month = 10; this.day = 28; */ } }
3.Java記憶體的主要劃分
JAVA物件導向(2)