[問題] 繼承如何使用同個instance
小弟寫了一個程式如下
public class test {
private int count; //計數器用
public int addCount(){
count++;
return count;
}
public test(){
System.out.println("new test");
count=0;
}
public static void main(String[] args) {
test1 t1 = new test1();
test2 t2 = new test2();
System.out.println(t1.addCount());
System.out.println(t2.addCount());
}
}
//另外有兩個class繼承test
public class test1 extends test {
public test1(){
System.out.println("new test1");
}
}
public class test2 extends test{
public test2(){
System.out.println("new test2");
}
}
而最後印出的結果 :
new test
new test1
new test
new test2
1
1
可是我想要兩個使用相同的計數器 也就是會印出
1
2
不知除了把count 改成 static外 有別的方法嗎?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 118.168.180.196
推
02/28 15:09, , 1F
02/28 15:09, 1F
推
02/28 15:14, , 2F
02/28 15:14, 2F
推
02/28 15:16, , 3F
02/28 15:16, 3F
→
02/28 15:19, , 4F
02/28 15:19, 4F
→
02/28 15:20, , 5F
02/28 15:20, 5F
→
02/28 15:20, , 6F
02/28 15:20, 6F
→
02/28 15:25, , 7F
02/28 15:25, 7F
→
02/28 15:27, , 8F
02/28 15:27, 8F
→
02/28 15:27, , 9F
02/28 15:27, 9F
推
02/28 15:50, , 10F
02/28 15:50, 10F
→
02/28 15:50, , 11F
02/28 15:50, 11F
→
02/28 16:01, , 12F
02/28 16:01, 12F
→
02/28 16:55, , 13F
02/28 16:55, 13F
推
02/28 20:11, , 14F
02/28 20:11, 14F