接口--interface

接口的定義格式:
    interface 接口名{
    }
接口的實現格式:
    class 類名 implements 接口名{
    }ide

代碼示例以下:學習

 1 interface A{
 2     String name = "接口A"; //默認修飾符爲 public static final 等價於 public static final String name = "接口A";
 3     public void print(); //默認修飾符爲:public abstract 等價於 public abstract void print();
 4 }
 5 
 6 class Demo implements A{
 7     public static void main(String[] args){
 8         Demo d = new Demo();
 9         // d.name = "Demo類"; //name爲常量不從新賦值
10         System.out.println("name: "+d.name);
11         d.print();
12     }
13     public void print(){
14         System.out.println("Demo類實現接口A中的方法");
15     }
16 }
View Code

接口的注意事項:
    一、接口是一個特殊的類。
    二、接口的成員變量默認的修飾符爲:public static final.即接口中的成員變量都是常量。
    三、接口中的方法都是抽象的方法,默認修飾符爲:public abstract
    四、接口沒有構造法。
    五、接口不能建立對象。
    六、接口是給類去實現的,非抽象類實現接口的時候,必需要把接口中的全部方法所有實現;抽象類能夠不徹底實現接口中的全部方法。
    七、一個類能夠實現多個接口。this

代碼示例以下:spa

 1 //需求:在現實生活中有部分同窗在學校期間只會學習,可是有部分學生除了學習外還會賺錢和談戀愛。
 2 
 3 //普通學生類
 4 class Student{
 5     String name;
 6     public Student(String name){
 7         this.name = name;
 8     }
 9     public void study(){
10         System.out.println(name+"學習");
11     }
12 }
13 
14 interface makeMoney{
15     public void canMakeMoney();
16 }
17 
18 interface FallInLove{
19     public void love();
20 }
21 
22 class makeMoneyStudent extends Student implements makeMoney,FallInLove{
23     public makeMoneyStudent(String name){
24         super(name);
25     }
26     public void canMakeMoney(){
27         System.out.println(name+"會賺錢");
28     }
29     public void love(){
30         System.out.println(name+"正在談戀愛");
31     }
32 }
33 
34 class StudentDemo{
35     public static void main(String[] args){
36         Student s1 = new Student("張三");
37         s1.study();
38         makeMoneyStudent s2 = new makeMoneyStudent("李四");
39         s2.study();
40         s2.canMakeMoney();
41         s2.love();
42     }
43 
44 }
View Code

接口的做用:
    一、程序解耦。
    二、定義約束規範。
    三、拓展功能。code

相關文章
相關標籤/搜索