JAVA面向對象(2)
阿新 • • 發佈:2017-10-28
col working 調用 面向對象 {} const mage stat oaf
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(intnum, 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)