Java接口代码实例及接口的特点

首次发布:2019-07-21
接口的特点
1、接口中的方法定义不需要Abstract来修饰,默认就是抽象的
2、接口不可以实例化,只能实现接口的类实例化,接口指向实现接口的类
3、接口中的方法不能有关键字private(想要方法被继承下去,子类不能防问),final(不能被复写),static(抽象方法针对的都是对象方法,static不能实例化)
4、接口中可以定义属性,但只能是一个常量,推荐使用 接口.属性(不推荐  new 实现方法.属性)
5、接口可以继承接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class TestPerson{
    public static void main(String[] args){
        Student sd=new Student();
        sd.Name="lqwvje";
        sd.Smoke();
        //System.out.println(sd.PI);//不推荐这么写sd.PI
        System.out.println(Person.PI);
    }
}
interface Person{
        //PI是个常量 补全是public static final double PI=3.14;
        double PI=3.14;
        public void Smoke();
}
class Student implements Person{
        public String Name;
        public void Smoke(){
        System.out.println(Name+"在厕所偷偷的抽烟");
    }
}
//-------------------接口继承--Strat-----------------------
interface A{
    public void MothodA();
    public void Mothod();
}  
interface B{
    public void MothodB();
    public void Mothod();
}  
interface C extends A,B{
    //C继承A和B接口
}  
class TestMothod implements C{
    public void MothodA(){
         
    }
    public void MothodB(){
         
    }
    public void Mothod(){
        // A和B都有这个方法 则它们会合并
    }
}
//-------------------接口继承--End-----------------------