java 唔work ..constructor 問題?

2010-11-08 11:27 am
suppose work ge java, 唔知點解唔work..
line 24 cannot find symbol, 明明一開始已經定義左??
請問有冇人知問題出左係邊?>< thx!!



class Info{
String name;
String number;
String dept;
Info(String s, String n, String g){
name=s;
number=n; dept=g;
}
void showInfo(String s){
System.out.println("My name is "+name+".");
}
void showInfo(String s, String n){
System.out.println("My name is "+name+".");
System.out.println("Student number is "+number+".");
}
void showInfo
(String s, String n, String g){
System.out.println("My name is "+name+".");
System.out.println("Student number is "+number+".");
System.out.println("Gakubu is "+dept+".");
}
public static void main(String[] args){
Info k=new Info();
k.showInfo("SSS");
k.showInfo("SSS","092");
k.showInfo("SSS","092","business");
}
}

回答 (1)

2010-11-08 2:27 pm
✔ 最佳答案
問題系:Info k=new Info();

because by default constructor takes 0 parameter, but if you initialize your own constructor the default constructor will be gone if you want to use the default constructor with the one you initialize you have to initialize to default constructor manually

in this case you need 3 constructor with 1 parameter, 2 parameter and 3 parameter
so you code will look like this:

Info:

Info(String s){
this(s,"","");
}

Info(String s, String n){
this(s,n,"");

}


Info(String s, String n, String g){
name=s;
number=n;
dept=g;
}




main:
Info a=new Info("sss");
Info b=new Info("SSS","092");
Info c=new Info("SSS","092","business");

a.showInfo("SSS");
b.showInfo("SSS","092");
c.showInfo("SSS","092","business");

hope this help
if you still have questions you can ask me

my msn: [email protected]
參考: me


收錄日期: 2021-04-23 23:07:19
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20101108000051KK00164

檢視 Wayback Machine 備份