微信登录

接口Interface - 类实现implements

Interface接口 声明

  1. [可见度] interface 接口名称 [extends 其他的接口名] {
  2. // 声明变量
  3. // 抽象方法
  4. }

Interface接口 可以继承

  1. public interface Football extends Sports
  2. {
  3. }

Interface接口 可以多继承

  1. public interface Hockey extends Sports, Event
  2. {
  3. }

Interface接口 实现implements

语法

  1. ...implements 接口名称[, 其他接口名称, 其他接口名称..., ...] ...

例子

  1. /* 文件名 : MammalInt.java */
  2. public class MammalInt implements Animal{
  3. public void eat(){
  4. System.out.println("Mammal eats");
  5. }
  6. public void travel(){
  7. System.out.println("Mammal travels");
  8. }
  9. public int noOfLegs(){
  10. return 0;
  11. }
  12. public static void main(String args[]){
  13. MammalInt m = new MammalInt();
  14. m.eat();
  15. m.travel();
  16. }
  17. }

保持一致的方法名,保持同返回值类型
如果是抽象类,那么就没必要实现该接口的方法
一个类只能继承一个类,但是能实现多个接口

Interface接口是一个抽象类型
Interface接口没有构造方法
Interface接口中不能含有静态代码块以及静态方法(用 static 修饰的方法)
Interface接口 包含 abstract抽象 但不用写

如果实现类覆盖了接口中的所有抽象方法,则此实现类就可以实例化
如果实现类没有覆盖接口中所有的抽象方法,则此实现类仍为一个抽象类

接口Interface - 类实现implements