Java Abstract class and Interface

Abstract Class

  1. 在定义class的时候必须有abstract 关键字
  2. 抽象方法必须有abstract关键字。
  3. 可以有已经实现的方法。
  4. 可以定义static final 的常量。
  5. 可以实现接口。
  6. 抽象类实现接口可以不实现接口中的抽象方法,而在其具体的子类中实现,但是这样代码的可读性不是很好。

Interface

  1. 在定义class的时候必须有interface 关键字
  2. 方法默认是抽象方法,不需要abstract关键字。
  3. 不能有已经实现的方法。
  4. 可以定义static final 的常量。
  5. 可以用extends关键字继承接口, 而不能用implements。应为interface只能包含未实现的抽象方法,所以无法使用implements关键字。
  6. 接口中的抽象方法不能使用privateprotected修饰符,可以不用修饰符或者使用public修饰符。在子类中实现接口的抽象方法的时候, 必须使用public关键字修饰。

Phone [interface]:

interface Phone{

    /**
     * getPhoneNumber()
     * @return
     */
    String getPhoneNumber();
}
View Code

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 }
View Code

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 }
View Code

GsmPhone [normal class]:

1 public class GsmPhone extends PhoneBase{
2 
3 @Override
4 void fun1() {
5 // TODO Auto-generated method stub
6 
7 }
8 }
View Code

//PhoneBase mPhoneBase1 = new PhoneBase(); //不能实例化一个抽象类
//Iphone p = new Iphone();//不能实例化一个接口
PhoneBase mPhoneBase = new GsmPhone();
Iphone iPhone = new GsmPhone();
Phone mPhone = new GsmPhone();

原文地址:https://www.cnblogs.com/kangyi/p/3252558.html