作者TonyQ (骨头)
看板java
标题Re: [问题] 请问建构子
时间Wed Apr 11 14:28:10 2007
※ 引述《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