计算机程序设计-2025版-教学案例-第02章

91 阅读1分钟

eg 2.4.3

class Animal {
    void eat() {
        System.out.println("Animal eats");
    }
}
 
class Dog extends Animal {
    void eat() {
        System.out.println("Dog eats");
    }
 
    void bark() {
        System.out.println("Dog barks");
    }
}
 
public class Main {
    public static void main(String[] args) {
        Animal myAnimal = new Dog(); // 隐式强制转换
        myAnimal.eat(); // 调用Dog的eat方法,但是myAnimal声明为Animal类型
        // myAnimal.bark(); // 编译错误,Animal类型没有bark方法
    }
}

eg 2.4.4

// 定义一个接口
interface Animal {
    void makeSound();
}
 
// 实现Animal接口的一个类
class Dog implements Animal {
    @Override
    public void makeSound() {
        System.out.println("Woof!");
    }
}
 
// 实现Animal接口的另一个类
class Cat implements Animal {
    @Override
    public void makeSound() {
        System.out.println("Meow!");
    }
}
 
public class InterfaceExample {
    public static void main(String[] args) {
        // 接口类型的引用可以指向实现类的实例
        Animal myPet = new Dog();
        myPet.makeSound(); // 输出: Woof!
 
        // 接口类型的引用可以动态指向不同的实现类实例
        myPet = new Cat();
        myPet.makeSound(); // 输出: Meow!
    }
}