-
为啥有接口?
-
接口就是一种规则
-
当我们需要给多个类同时定义规则的时候,就可以啊定义接口
-
比如:
父类为(动物)
子类为:狗
青蛙
兔子
当我们需要定义一个游泳的方法或规则时,我们不能吧他写到父类里面。因为兔子不会游泳,这个时候就需要定义接口,然后让狗和青蛙连接到这个游泳接口
-
-
什么是规则
-
接口的定义和使用
-
练习
青蛙类
package lianxi1; public class qw extends dw implements jiekou{ public qw() { } public qw(String name, int age) { super(name, age); } @Override public void eat() { System.out.println("青蛙吃苍蝇"); } @Override public void youyong() { System.out.println("蛙泳"); } }
狗类
package lianxi1; public class dog extends dw implements jiekou{ public dog() { } public dog(String name, int age) { super(name, age); } @Override public void eat() { System.out.println("狗吃骨头"); } @Override public void youyong() { System.out.println("狗刨"); } }
兔子类
package lianxi1; public class tuzi extends dw{ public tuzi() { } public tuzi(String name, int age) { super(name, age); } @Override public void eat() { System.out.println("兔子吃艹"); } }
动物类
package lianxi1; public abstract class dw { private String name; private int age; public dw() { } public dw(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(); }
测试类
package lianxi1; public class teat { public static void main(String[] args) { dog d = new dog(); d.youyong(); d.eat(); qw q = new qw(); q.eat(); q.youyong(); tuzi t = new tuzi(); t.eat(); } }
接口
package lianxi1; public interface jiekou { public abstract void youyong (); }
-