JavaSE-11.3.3【接口案例-猫和狗】
package day2.yubaby03.p3; /* 3.4 接口案例-猫和狗 */ public class AnimalDemo { public static void main(String[] args) { Jumpping j = new Cat(); j.jump(); Animal a = new Cat(); a.setName("tom"); a.setAge(1); System.out.println(a.getName() + "," + a.getAge()); a.eat(); // a.jump(); //error ((Cat) a).jump(); //ok //or Cat c = (Cat)a; c.jump(); //ok a = new Cat("sam", 2); System.out.println(a.getName() + "," + a.getAge()); a.eat(); ((Cat) a).jump(); //从上述可以看出,通过接口得到的对象只能调用接口的成员方法,通过父类的只能调用父类的 //更常用的写法:(子类/实现类,既可以调用接口中的方法也可以调用父类中的) Cat cat = new Cat(); cat.setName("it"); cat.setAge(3); System.out.println(cat.getName() + "," + cat.getAge()); cat.eat(); cat.jump(); } }
package day2.yubaby03.p3; 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 void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public int getAge() { return age; } public abstract void eat(); }
package day2.yubaby03.p3; public interface Jumpping { // public abstract void jump(); //或 void jump(); }
package day2.yubaby03.p3; public class Cat extends Animal implements Jumpping{ public Cat() { } public Cat(String name, int age) { super(name, age); } @Override public void eat() { //重写自父类 System.out.println("猫猫吃饭了"); } @Override public void jump() { //重写自接口 System.out.println("猫猫跳高了"); } }
package day2.yubaby03.p3; public class Dog extends Animal implements Jumpping{ public Dog() { } public Dog(String name, int age) { super(name, age); } @Override public void eat() { System.out.println("狗狗吃饭了"); } @Override public void jump() { System.out.println("狗狗跳高了"); } }