一.为什么有接口?
接口:就是一种规则。
二.接口的定义和使用
1.接口用关键字interface来定义
public interface 接口名{}
2.接口不能实例化
3.接口和类之间是实现关系,通过implements关键字表示
4.接口的子类(实现类)
注意1:
接口和类的实现关系,可以单实现,也可以多实现。
public class 类名 implements 接口名1,接口名2{
}
注意2:
实现类还可以在继承一个类的同时实现多个接口。
publi class 类名 extends 父类 implements 接口名1,接口名2{
}
三.案例
Animal类:
package day;public abstract class Animal {private String name;private int age;public Animal() {}public Animal(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public abstract void eat();
}
Swim接口:
package day;public interface Swim {public abstract void swim();
}
Dog类:
package day;public class Dog extends Animal implements Swim {@Overridepublic void eat() {System.out.println("狗吃骨头");}@Overridepublic void swim() {System.out.println("狗刨");}
}
Forg类:
package day;public class Test {public static void main(String[] args) {Forg f = new Forg("小青", 1);System.out.println(f.getName() + "," + f.getAge());f.eat();f.swim();// 创建兔子的对象Rabbit r = new Rabbit("小白", 2);System.out.println(r.getAge() + r.getAge());r.eat();}
}
Raabit类:
package day;public class Rabbit extends Animal {@Overridepublic void eat() {System.out.println("兔子在吃胡罗波");}public Rabbit() {}public Rabbit(String name, int age) {super(name, age);}
}
Test测试类:
package day;public class Test {public static void main(String[] args) {Forg f = new Forg("小青", 1);System.out.println(f.getName() + "," + f.getAge());f.eat();f.swim();// 创建兔子的对象Rabbit r = new Rabbit("小白", 2);System.out.println(r.getAge() + r.getAge());r.eat();}
}
运行的结果: