Java中的接口

----------接口(interface)----------

接口能够理解为一种特殊的抽象类

编写接口语法例如以下:

[修饰符] interface 接口名 extends 父接口1,父接口2,...{
 //常量定义
 //方法定义
}

实现接口语法例如以下:

class 类名 extends 父类名 implements 接口1,接口2,...{
 //类成员
}

接口具有下面特点:

1.接口不能够被实例化

2.接口中不可有非抽象方法

3.接口中不能有构造方法

4.接口中能够定义常量,不能够定义变量

5.接口能够继承多个接口,不能够继承类

6.接口的实现类必须实现接口的所有方法,否则必须定义为抽象类

接口的优点:

1.弥补了Java中仅仅支持单继承的缺点(这里说的单继承指类,是说一个类仅仅能有一个直接父类)

2.提高了软件的可扩展性

3.减少了耦合性


以下一段程序是接口的体现:

/**
* 腿
*/
public interface Useleg {
    void run();//跑步
    void walk();//行走
}
/**
* 嘴
*/
public interface Usemouth {
    void speak();//讲话
    void eat();//吃饭
}
/**
* 耳朵
*/
public interface Useear {
    void hearMusic();//听音乐
}
/**
* 眼睛
*/
public interface Useeye {
    void seeFilm();//看电影
}
/**
* 人
*
* 实现接口 腿
*
* 实现接口 嘴

* 实现接口 耳朵
*
* 实现接口 眼睛
*/
public class Person implements Useleg, Usemouth, Useear, Useeye{

    String name;//姓名
    int age;//年龄
    String adddress;//地址
    String ID;//ID

    public void run(){
        System.out.println("I am running.");
    }
    public void walk(){
        System.out.println("I am walking.");
    }
    public void speak(){
        System.out.println("I am speaking.");
    }
    public void eat(){
        System.out.println("I am eating.");
    }
    public void hearMusic(){
        System.out.println("I am leistening to music.");
    }
    public void seeFilm(){
        System.out.println("I am seeing a film.");
    }
}

public class Test {  
    public static void main(String[] args) {
        Person p = new Person();
        p.seeFilm();
 ...
    }
}

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/yutingliuyl/p/6710676.html