抽象類不能new對象的,只能被子類繼承。如果抽象類中方法是抽象方法,那麼子類必須實例化此方法,否則不需要去此方法!抽象類沒有構造方法,也不能實例化.
靜態變量,因爲初始化的時候會在內存中開闢一塊地方存儲,所以不論對他進行什麼操作,都是對同一個內存進行操作,也就是說對這個靜態變量操作的結果是會累加的。
比如 下面的程序:
public class Ruckus {
public static void main(String[] args) {
// new dog的時候會實例化Counter類的count變量,count=1,static變量只初始化一次,所以再就new
// dog()的話就不會再初始化count變量了.
Dog dogs[] = { new Dog(), new Dog() };
for (int i = 0; i < dogs.length; i++) {
// 這裏對count變量進行++,是的count=2;因爲count是static的,所以對他的操作會累加,否則將不會累加,只是初始化。
dogs[i].woof();
int num = Dog.getCount();
// 也就是說如果count不是靜態的,那麼這裏的num每次都會是0
System.out.println(num);
}
Cat cats[] = { new Cat(), new Cat(), new Cat() };
for (int i = 0; i < cats.length; i++)
cats[i].meow();
System.out.print(Dog.getCount() + " woofs and ");
System.out.println(Cat.getCount() + " meows");
}
}
class Counter {
private static int count = 0;
public static final synchronized void increment() {
count++;
}
public static final synchronized int getCount() {
return count;
}
}
class Dog extends Counter {
public Dog() {
}
public void woof() {
increment();
}
}
class Cat extends Counter {
public Cat() {
}
public void meow() {
increment();
}
}
每次new一個Dog對象,或者是Cat對象,並不會對count的值產生影響,但是
woof()
這個方法調用一次就會給count加1,那麼因爲這樣的操作對static變量來說是累加的,所以count會一只加到5纔算結束。
結果可想而知:5 woofs and 5 meows