Re: [問題] 請問建構子
※ 引述《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
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 3 之 7 篇):