接口--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

相关文章
相关标签/搜索