标签:测试 ati over dog work ima animal nim 就是
上文还没有写完,这一篇继续
https://www.cnblogs.com/qianjinyan/p/10824576.html
接口实现关系,和继承区别不是很大,
接口和继承从定义上,无非一个对象能实现两个接口,解决了子类只能单继承的问题
先来两个接口,一个是动物类,一个是哺乳动物类,先不要管这两个类的关系,这就是没有相互关系的两个接口
public interface Animal { void eat(); void work(); }
public interface Mammal { }
public class Cat implements Animal,Mammal{ public void eat() { System.out.println("===我是猫咪我要吃鱼"); } public void work() { System.out.println("===我是猫咪我负责抓老鼠"); } public int numberOfLegs(){ return 4; } }
public class Dog implements Animal,Mammal { @Override public void eat() { System.out.println("====我是小狗我要吃骨头"); } @Override public void work() { System.out.println("====我是小狗我负责看家"); } public void travel(){ System.out.println("Dog travels"); } public int numberOfLegs(){ return 4; } }
public class Chicken implements Animal { public void eat() { System.out.println("===我是鸡仔我要吃粗粮"); } public void work() { System.out.println("===我是鸡仔我负责下蛋"); } public int numberOfLegs(){ return 2; } }
测试类:
public class TestM { public static void main(String args[]){ Cat m = new Cat(); m.eat(); m.work(); int number =m.numberOfLegs(); System.out.println(number); Animal animal = new Cat(); animal.eat(); animal.work(); int animalnumber =((Cat)animal).numberOfLegs(); System.out.println(number); Mammal mammal = new Cat(); ((Cat)mammal).eat(); ((Cat)mammal).work(); int mammalnumber =((Cat)mammal).numberOfLegs(); System.out.println(number); Animal ch = new Chicken(); ch.eat(); ch.work(); int ch_legs =((Chicken)ch).numberOfLegs(); System.out.println(ch_legs); } }
标签:测试 ati over dog work ima animal nim 就是
原文地址:https://www.cnblogs.com/qianjinyan/p/10825104.html