java中implements和extends的使用小結


  1 interface InterfaceOne
  2 {
  3 	void sayHello();
  4 }
  5 /*接口之間要用extends關鍵字
 6 interface InterfaceTwo implements interfaceOne
 7 {
 8 
 9 }*/
 10 interface InterfaceThree extends InterfaceOne
 11 {
 12 }
 13 //抽象類可以不用實現接口或父抽象類的方法。
 14 abstract class AbstractClassOne implements InterfaceOne
 15 {
 16 }
 17 abstract class AbstractClassTwo extends AbstractClassOne
 18 {
 19 }
 20 //非抽象類一定要實現接口內的方法。
 21 class ClassOne implements InterfaceOne
 22 {
 23 	public void sayHello() {};
 24 }

如果遇到一個接口中需要實現的方法很多,但我們只需要用其中的幾個方法,
假設需要繼承的接口是:

  1 interface A
  2 {
  3 	void operation1();
  4 	void operation2();
  5 	……
  6 	void operation100();
  7 }

假設我們只需要使用其中的operation5
如果直接繼承這個接口,則所有方法都要實現:

  1 class Class implements A
  2 {
  3 	public void operation1(){}
  4 	public void operation2(){}
  5 	……
  6 	public void operation5(){
  7 		/*
 8 		 * operation5
 9 		 */
 10 	}
 11 	……
 12 	public void operation100(){}
 13 }

這樣十分麻煩,所以可以使用如下方法解決,
新建一個抽象類(如果規定一個接口方法一定要實現,則把它設為抽象方法,比如說operation99必須要實現):

  1 abstract class Abstract implements A
  2 {
  3 	public void operation1(){}
  4 	public void operation2(){}
  5 	……
  6 	public void operation98(){}
  7 	//這里的operation99就不提供虛實現,從而必須要在具體類中實現它。
  8 	public void operation100(){}
  9 }

為所有接口方法提供一個虛實現,今后要利用這個接口只需要進行如下操作:

  1 class Class extends Abstract
  2 {
  3 	//重寫operation5
  4 	public void operation5(){
  5 		/*
 6 		 * operation5
 7 		 */
  8 	}
  9 	//實現operation99
 10 	public void operation99(){
 11 		/*
 12 		 * operation99
 13 		 */
 14 	}
 15 }

這樣就不必為每個接口方法提供實現了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM