定义和使用
接口是一种规则,是对行为的抽象
1.public interface 接口名{}
2.接口不能创建对象
3.接口和类是实现关系,通过implements关键字表示
public class 类名 implements 接口名{}
public class 类名 implements 接口名1,接口名2{}
4.接口的子类要么重写接口所有的抽象方法,要么是一个抽象类
5.子类可以在继承一个类的同时实现多个接口
public class 类名 extends 父类 implements 接口名1,接口名2{}
案例
父类Animal类
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类
public interface Swim {
public abstract void swim();
}
子类Frog类
public class Frog extends Animal implements Swim{
public Frog() {
}
public Frog(String name, int age) {
super(name, age);
}
@Override
public void eat() {
System.out.println("青蛙在吃虫子");
}
@Override
public void swim() {
System.out.println("青蛙在蛙泳");
}
}
子类Rabbit类
public class Rabbit extends Animal{
public Rabbit() {
}
public Rabbit(String name, int age) {
super(name, age);
}
@Override
public void eat() {
System.out.println("兔子在吃胡萝卜");
}
}
测试类
public class Test {
public static void main(String[] args) {
//创建青蛙的对象
Frog f = new Frog("小青",1);
System.out.println(f.getName() + ", " + f.getAge());
f.eat();
f.swim();
//创建兔子的对象
Rabbit r = new Rabbit("小白",2);
System.out.println(r.getName() + ", " + r.getAge());
r.eat();
}
}