文章出處
View Code
View Code
View Code
View Code
文章列表
Abstract Class
- 在定義class的時候必須有abstract 關鍵字
- 抽象方法必須有abstract關鍵字。
- 可以有已經實現的方法。
- 可以定義static final 的常量。
- 可以實現接口。
- 抽象類實現接口可以不實現接口中的抽象方法,而在其具體的子類中實現,但是這樣代碼的可讀性不是很好。
Interface
- 在定義class的時候必須有interface 關鍵字
- 方法默認是抽象方法,不需要abstract關鍵字。
- 不能有已經實現的方法。
- 可以定義static final 的常量。
- 可以用extends關鍵字繼承接口, 而不能用implements。應為interface只能包含未實現的抽象方法,所以無法使用implements關鍵字。
- 接口中的抽象方法不能使用private和protected修飾符,可以不用修飾符或者使用public修飾符。在子類中實現接口的抽象方法的時候, 必須使用public關鍵字修飾。
Phone [interface]:

interface Phone{ /** * getPhoneNumber() * @return */ String getPhoneNumber(); }
Iphone [interface]:

1 public interface Iphone extends Phone{ 2 3 /** 4 * getPhoneName() 5 * @return 6 */ 7 String getPhoneName(); 8 9 /** 10 * getPhoneType() 11 * @return 12 */ 13 int getPhoneType(); 14 }
PhoneBase [abstract class]:

1 public abstract class PhoneBase implements Iphone{ 2 3 private static final String TAG = "PhoneBase"; 4 5 abstract void fun1(); 6 7 void fun2(){ 8 System.out.println("This is fun2"); 9 } 10 11 @Override 12 public String getPhoneName() { 13 // TODO Auto-generated method stub 14 return null; 15 } 16 17 @Override 18 public int getPhoneType() { 19 // TODO Auto-generated method stub 20 return 0; 21 } 22 23 @Override 24 public String getPhoneNumber() { 25 // TODO Auto-generated method stub 26 return null; 27 } 28 }
GsmPhone [normal class]:

1 public class GsmPhone extends PhoneBase{ 2 3 @Override 4 void fun1() { 5 // TODO Auto-generated method stub 6 7 } 8 }
//PhoneBase mPhoneBase1 = new PhoneBase(); //不能實例化一個抽象類
//Iphone p = new Iphone();//不能實例化一個接口
PhoneBase mPhoneBase = new GsmPhone();
Iphone iPhone = new GsmPhone();
Phone mPhone = new GsmPhone();
文章列表
全站熱搜