Java的建構函式與解構函式(筆記1)
阿新 • • 發佈:2018-11-26
已Mydate為例:
package text1; public class MyDate { int year; int month; int day; //1.建構函式 public MyDate(int y,int m,int d) { year = y; month = m; day = d; } //2.預設建構函式 public MyDate() {/* year = 2018; month = 11; day = 11; */ this(2018,11,13);//在構造方法中,this必須是第一行語句 } //建構函式過載 //4拷貝建構函式 public MyDate(MyDate d) { //year = d.year; //month = d.month; //day = d.day; this(d.year,d.month,d.day); } //解構函式 public void finalize() { System.out.println("空間已釋放!"); } //String函式,輸出類物件 public String toString() { return year + "年" + month + "月" + day + "日"; } //判斷該類的兩個物件是否相等只能用equals()方法; //java不支援運算子過載,對於=、!=只能判斷兩個物件是否引用同一個例項 public boolean equals(MyDate d) { return this==d || d!=null && this.year==d.year && this.month==d.month && this.day==d.day; //this表呼叫當前方法的物件;對於this.year,this.month,this.day中this可省略; //this==d判斷是否指向同一例項 } public static void main(String arg[]) { MyDate d1 = new MyDate(2018,11,10); System.out.println(d1.toString()); //d1.finalize(); MyDate d2 = new MyDate(); System.out.println(d2.toString()); //d2.finalize(); MyDate d3 = new MyDate(d2); System.out.println(d3.toString()); //d3.finalize(); //System.gc();//釋放所有垃圾 System.out.println("d1與d2是否為同一天: " + d1.equals(d2)); System.out.println("d2與d3是否為同一天 : " + d2.equals(d3)); } }