1. 定义接口 IJumping

public interface IJumping { void jump(); }

  1. 定义抽象动物类 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();

}

  1. 定义具体猫类 Cat

public class Cat extends Animal implements IJumping { private int cuteLevel;

public Cat() {
}

public Cat(String name, int age, int cuteLevel) {
    super(name, age);
    this.cuteLevel = cuteLevel;
}

public int getCuteLevel() {
    return cuteLevel;
}

public void setCuteLevel(int cuteLevel) {
    this.cuteLevel = cuteLevel;
}

@Override
public void eat() {
    System.out.println(getName() + " is eating fish.");
}

@Override
public void jump() {
    System.out.println(getName() + " is jumping.");
}

}

  1. 定义具体狗类 Dog

public class Dog extends Animal implements IJumping { private double weight;

public Dog() {
}

public Dog(String name, int age, double weight) {
    super(name, age);
    this.weight = weight;
}

public double getWeight() {
    return weight;
}

public void setWeight(double weight) {
    this.weight = weight;
}

@Override
public void eat() {
    System.out.println(getName() + " is eating meat.");
}

@Override
public void jump() {
    System.out.println(getName() + " is jumping.");
}

}

  1. 定义测试类 TestAnimal

public class TestAnimal { public static void main(String[] args) { Cat cat = new Cat("Tom", 3, 5); Dog dog = new Dog("Snoopy", 5, 10.5);

    cat.eat();
    cat.jump();

    dog.eat();
    dog.jump();
}

}

输出结果:

Tom is eating fish. Tom is jumping. Snoopy is eating meat. Snoopy is jumping

1 采用接口的思想实现猫和狗类。【需求】:对猫和狗进行训练他们就可以跳高。这里增加了跳高功能。请采用抽象类和接口实现猫狗案例并在测试类中进行单元测试。【思路】: 1 定义接口: Ijumpping 成员方法:跳高 2 定义抽象动物类Animal: 变量:姓名、年龄;构造方法:

原文地址: https://www.cveoy.top/t/topic/eF3b 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录