5 changed files with 43 additions and 0 deletions
@ -0,0 +1,3 @@ |
|||
public abstract class Animal { |
|||
public abstract void makeSound (); |
|||
} |
|||
@ -0,0 +1,6 @@ |
|||
public class Cat extends Animal{ |
|||
@Override |
|||
public void makeSound() { |
|||
System.out.println("猫:喵喵喵"); |
|||
} |
|||
} |
|||
@ -0,0 +1,11 @@ |
|||
public class Dog extends Animal implements Swimmable{ |
|||
@Override |
|||
public void makeSound() { |
|||
System.out.println("狗:汪汪汪"); |
|||
} |
|||
|
|||
@Override |
|||
public void swim() { |
|||
System.out.println("狗会游泳"); |
|||
} |
|||
} |
|||
@ -0,0 +1,20 @@ |
|||
public class Main { |
|||
public static void main(String[] args){ |
|||
Animal dog = new Dog(); |
|||
Animal cat = new Cat(); |
|||
|
|||
System.out.println("动物叫声"); |
|||
dog.makeSound(); |
|||
cat.makeSound(); |
|||
|
|||
System.out.println("是否会游泳"); |
|||
if (dog instanceof Swimmable){ |
|||
((Swimmable) dog).swim(); |
|||
} |
|||
if (cat instanceof Swimmable){ |
|||
((Swimmable) cat).swim(); |
|||
} else { |
|||
System.out.println("猫不会游泳"); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,3 @@ |
|||
public interface Swimmable { |
|||
void swim(); |
|||
} |
|||
Loading…
Reference in new issue