Re: [問題] 請問建構子

看板java作者 (骨頭)時間18年前 (2007/04/11 14:28), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串3/7 (看更多)
※ 引述《towalking (啊哈)》之銘言: : 不好意思,我是個初學者,有個問題想請教: : 如果 class 裡有建構子設定,如: : public Date (int m, int d, int y) //建構子其一 : { : month = m; : day = d; : year = y; : } : 那我可以寫 Date birthday = new Date(); : 也就是沒給任何參數,這樣可以嗎? : 因為程式跑起來有問題,所以我假設這是不行的, : 於是我又寫了另一個建構子: : public anDate(){} //建構子其二 : 想法是以這個建構子創出來的 instance 裡面是空白的, : 不過跑程式又出現問題了… : 我知道 C++ 可以有內容空白的建構子, : 想請問 java 也可以嗎?該怎麼寫? : 謝謝回答~ 你會出現問題應該是因為 Date()是預設class new Date()的時候發生參照錯誤 , 命名要盡量避開 API有的類別名稱 http://java.sun.com/j2se/1.5.0/docs/api/java/util/Date.html java當然可以有空白建構子 以你的例子來講 class myDate{ int year; int month; int day; public myDate(){} public myDate(int year,int mon,int day){ this.year=year; month=mon; this.day=day; } } class PracticeOnly { public static void main( String[] arg ) throws Exception{ myDate m=new myDate(); myDate mm=new myDate(2006,1,1); //work } } -- String temp="relax"; | Life just like programing while(buringlife) String.forgot(temp); | to be right or wrong while(sleeping) brain.setMemoryOut(); | need not to say stack.push(life.running); | the compiler will stack.push(scouting.buck()); | answer your life stack.push(bowling.practice()); | Bone everything -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.134.27.68
文章代碼(AID): #1677_zUa (java)
討論串 (同標題文章)
文章代碼(AID): #1677_zUa (java)