You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

23 lines
625 B

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Buddy");
Cat cat = new Cat("Kitty");
Bird bird = new Bird("Tweety");
// 调用 Pet 接口方法
dog.play();
cat.play();
// Bird 没有实现 Pet所以不能调用 play()
bird.fly();
// 也可以通过 instanceof 检查
if (dog instanceof Pet) {
System.out.println(dog.getName() + " is a pet.");
}
if (!(bird instanceof Pet)) {
System.out.println(bird.getName() + " is not a Pet implementation.");
}
}
}