13、interface,接口

来源:互联网 发布:浪腾软件 编辑:程序博客网 时间:2024/06/05 23:52
一 interface
1.1 interface,接口
  • 多个无关的类可以实现同一个接口
  • 一个类可以实现多个无关的接口
  • 与继承关系类似,接口与实现类之间存在多态性
  • 定义Java类的语法格式:

<modifier>  class  <name>  [extends  <superclass>]  [implements  <interface>  [, <interface>] ] {}


接口(interface)是抽象方法和常量值的定义的集合,从本质来来说,接口是一种特殊的抽象类,这种抽象类只包含常量和方法的定义,而没有变量和方法的实现

如下一段代码

public interface Runner {
     public static finalint id = 1;

     public void start();     //在interface中无需写abstract
     public void run();
     public void stop();
}

1.1.1 接口的特性
  • 接口可以多重实现
  • 接口可以继承其他的接口,并添加新的属性和抽象方法
  • 接口中所有方法都是抽象的
  • 即使没有显示的将接口中的成员用public标识,也是public访问类型的
  • 接口中变量默认用public static final标识,所以接口中定义的变量就是全局静态常量
  • 接口用关键字interface表示
    • 格式:interface  接口名 {}
    • 类实现接口用implements表示,格式:
      • class  类名  implements  接口名 {}

如下面一段代码

interface Singer {
    public void sing();
    public void sleep();
}

interface Painter {
    public void paint();
    public void eat();
}

class Student implements Singer {
    private String name;

    Student(String name) {
        this.name = name;
    }

    public void study() {
        System.out.println("studying");
    }

    public String getName() {
        return name;
    }

    public void sing() {
        System.out.println("student is singing");
    }

    public void sleep() {
        System.out.println("student is sleeping");
    }
}

class Teacher implements Singer,Painter {
    private String name;

    public String getString() {
        return name;
    }

    Teacher(String name) {
        this.name = name;
    }

    public void teacher() {
        System.out.println("teaching");
    }

    public void sing() {
        System.out.println("teacher is singing");
    }

    public void sleep() {
        System.out.println("teacher is sleeping");
    }

    public void paint() {
        System.out.println("teacher is painting");
    }

    public void eat() {
        System.out.println("teacher is eating");
    }
}

public class TestInterface {
    public static void main(String[] args) {
        Singer s1 = new Student("le");
        s1.sing();
        s1.sleep();
        Singer s2 = new Teacher("steven");
        s2.sing();
        s2.sleep();
        Painter p1 = (Painter)s2;
        p1.paint();
        p1.eat();
    }
}



1.2 练习
1.2.1 练习1
写一个飞行接口,方法有飞行;
小鸟实现该接口,飞机实现该接口,超人实现该接口

public class Test {
     public static void main(String[] args) {
          Flyable f1 = new Bird();
          Flyable f2 = new Plane();
          Flyable f3 = new SuperMan();
          f1.fly();
          f2.fly();
          f3.fly();
     }
}
interface Flyable {
     public void fly();
}

class Bird implements Flyable {
     public void fly() {
          System.out.println("小鸟飞翔");
     }
}

class Plane implements Flyable {
     public void fly() {
          System.out.println("飞机飞翔");
     }
}

class SuperMan implements Flyable {
     public void fly() {
          System.out.println("超人飞翔");
     }
}