Java繼承的使用

yoyochina發表於2009-02-17

   這裡的問題是分別求出A和B的例項的個數。如下面的程式碼。

 

class Counter
{
	private static int count = 0;
	public static synchronized void Add() { count++; }
	public static synchronized int getNumber() { return count; }
}

class A extends Counter
{
	public A() { }
	public void addA() { Add(); }
}

class B extends Counter
{
	public B() { }
	public void addB() { Add(); }
}

public class Test 
{
	public static void main(String[] args)
	{
		A[] aa = { new A(), new A() };
		B[] bb = { new B(), new B(), new B() };
		
		for(int i=0; i<aa.length; i++) { aa[i].addA(); }
		for(int i=0; i<bb.length; i++) { bb[i].addB(); }
		
		System.out.println(A.getNumber() + " A and " + B.getNumber() +" B");
	}
}

 

       輸出結果為:5 A and 5 B

 

      對這個結果還是比較好理解的,因為Counter類中的count是static型別的。

 

      但是這裡要說的是,這裡的繼承關係使用的合適嗎?類A和類B都不是“計數器(Counter)”,所以這裡使用繼承關係不合適。

 

      在設計一個類的時候,如果該類構建於另一個類的行為之上,那麼你有兩種選擇:一種是繼承,即一個類擴充套件另一個類;另一種是組合,即在一個類中包含另一個類的一個例項。選擇的依據是,一個類的每一個例項都是另一個類的一個例項,還是都有另一個類的一個例項。在第一種情況應該使用繼承,而第二種情況應該使用組合。當你拿不準時,優選組合而不是繼承。

 

      下面是重新設計的類。類A和類B中各自有一個計數器域,而且這些計數器域是靜態的。

 

class A
{
	private static int count = 0;
	public A() { }
	public void addA() { count++; }
	public static int getNumber() { return count; }
}

class B
{
	private static int count = 0;
	public B() { }
	public void addB() { count++; }
	public static int getNumber() { return count; }
}

public class Test 
{
	public static void main(String[] args)
	{
		A[] aa = { new A(), new A() };
		B[] bb = { new B(), new B(), new B() };
		
		for(int i=0; i<aa.length; i++) { aa[i].addA(); }
		for(int i=0; i<bb.length; i++) { bb[i].addB(); }
		
		System.out.println(A.getNumber() + " A and " + B.getNumber() +" B");
	}
}

 

輸出結果為:2 A and 3 B

 

相關文章