接口

接口的定义和使用

     接口用关键字interface来定义( public interface 接口名{} )。

     接口不能实例化,接口和类之间是实现关系,通过implements实现。   

   类可以实现多个接口,要声明出所有接口(public class ... implements 接口1, 接口2{})。

   类可以在继承的同时实现接口(public class ... extends ... implements 接口1, 接口2{})。

代码示例:

interface inte{
    int a = 1;
    void show();//抽象的,无法实例化
}
class cla implements inte{

    @Override
    public void show() {
        // TODO Auto-generated method stub
        System.out.println("show");
    }
    
}
public class Main {
    public static void main(String[] args) {

        cla cla = new cla();
        cla.show();
        System.out.println(cla.a);
    }

}
//输出:
show
1

注:在接口定义的常量默认为final static

当类在实现多个接口时,若这些接口中有些方法的名称相同,则只需覆盖一次即可

posted @ 2023-11-04 18:46  kandhera  阅读(14)  评论(0)    收藏  举报