作者eieio (好多目标)
看板java
标题Re: [问题] 建构子问题
时间Thu Mar 15 00:04:22 2012
※ 引述《cyberwizard (Gavin)》之铭言:
: public class test {
: static int c;
:
: public static void main(String[] args) {
: int a = 1;
: int b = 2;
: //new test(a, b);
: System.out.printf("两数字相加 %d, %d 答案为 %d %n ", a, b, c);
: }
:
: public test(int a, int b){
: c =a + b;
: }
: }
:
: 去掉不必要得部份,这样执行会得到
: 两数字相加 1, 2 答案为 0
:
: 把注解去掉,会得到
: 两数字相加 1, 2 答案为 3
:
: 虽然物件建构子当作方法用很怪,但是功能还是正常的
:
: --
:
※ 发信站: 批踢踢实业坊(ptt.cc)
: ◆ From: 140.123.85.140
: 推 jodoken:建构值当方法用很奇怪吗? 03/14 18:34
: 推 LaPass:非常奇怪.... 03/14 19:28
: 推 mars90226:建构子就是在你需要那个物件时才呼叫阿~ 03/14 22:15
正常的用法
public class Coffee {
int c; // this is non-static
public static void main(String[] args) {
int a = 1;
int b = 2;
Coffee coffee = new Coffee(a, b); // 新的物件要接
System.out.println("(a,b,c)", a, b, coffee.c);
}
public Coffee(int a, int b) {
c = a + b;
}
}
Constructor (中文是建构子?) 的确是一个不必宣告 return type 的 method
,但这不表示它没有回传东西。以上面的例子来说,constructor 回传的东西就
是 Coffee。如果需要一个没有回传的 method,那就用 void 来宣告,像上面的
main() 就是了。
原 po 的例子里另一个不好的 pattern,是在 constructor 里面改 static
variable。Static variable 是所有同 class 的 object 共用的,不应该在新
建一个 object 时更改。假设上面的 c 表示咖啡有没有加奶精好了,如果你让
它是 static 的话,表示你自己点一杯咖啡加奶精时,会让餐厅里所有其他人的
咖啡一起加奶精,这听起来就很怪 XD
--
If I don't know I don't know, I think I know
If I don't know I know, I think I don't know
── R. D. Laing
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 207.171.191.60