1.什么是接口?
接口就是给出一些没有实现的方法,封装到一起,当某一个类要使用的时候再实现出来。
2.接口的语法
interface name{
attributes
methods
}
比如如下USB接口
public interface Usb {
                
                public void start();
                public void stop();
                
}
 
3.实现接口的类
public class name implements interfacename{
this.attributes
this.methods
implement methods
}
Phone类实现USB接口中的方法
public class Phone implements Usb{
                public void start(){
                                System.out.println("using phone usb");
                }
                public void stop(){
                                System.out.println("closing phone usb");
                }
}
 
Camera类实现USB接口中的方法
public class Camera implements Usb {
                public void start(){
                                System.out.println("camera starting work");
                }
                public void stop(){
                                System.out.println("camera stopping work");
                }
}
 
4.使用接口
Computer调用USB接口
public class Computer {
            //调用usb接口
                public void work(Usb usb)
                {
                                usb.start();
                                usb.stop();
                }
}
 
 
主类
public class main {
                public static void main (String args []){
                                // 手机和相机
                                Phone phone = new Phone();
                                Camera camera = new Camera();
// 电脑
                                Computer computer  = new Computer();
                                // 分别调用他们的接口
                                computer.work(camera);
                                computer.work(phone);
                }
} 
运行结果如下

5. 如何定义默认接口
定义语法如下
public interface name {
定义默认接口
default methods()
{
statements
}
普通接口
public void stop();
}
比如
public interface Usb {
                
                default public void start()
                {
                                System.out.println("Usb working..");
                }
                public void stop();
}
 
 
使用接口的注意事项
1.接口中的属性只能是final的,而且是public static final 修饰,比如:int a=1 实际上是:public static final a=1;(必须需要初始化)
2.接口的访问形式 interface.name.methodname
3.接口只能继承接口(还可以多继承)
4.接口的修饰符(访问权限)只能是public 或者默认。(和抽象类很像())
5.一个类可以实现多个接口
比如:
public class Phone implements Usb,Usb1{
                public void start(){
                                System.out.println("using phone usb");
                }
                public void stop(){
                                System.out.println("closing phone usb");
                }
}
 
                

















