11 changed files with 62 additions and 0 deletions
|
Before Width: | Height: | Size: 81 KiB After Width: | Height: | Size: 81 KiB |
@ -0,0 +1,7 @@ |
|||
package w6; |
|||
|
|||
public abstract class Animal { |
|||
|
|||
public abstract void makeSound(); |
|||
} |
|||
|
|||
@ -0,0 +1,28 @@ |
|||
package w6; |
|||
|
|||
public class AnimalTest { |
|||
public static void main(String[] args) { |
|||
//多态调用Animal抽象类
|
|||
System.out.println("===动物叫声测试==="); |
|||
Animal dog1=new Dog(); |
|||
Animal cat1=new Cat(); |
|||
dog1.makeSound(); |
|||
cat1.makeSound(); |
|||
//多态调用Swimmable接口
|
|||
System.out.println("\n===游泳能力测试==="); |
|||
Swimmable swimmer = new Dog(); |
|||
swimmer.swim(); |
|||
//数组遍历多态演示
|
|||
System.out.println("\n===数组多态遍历==="); |
|||
Animal[] animals={new Dog(),new Cat()}; |
|||
for (Animal animal :animals) { |
|||
animal.makeSound(); |
|||
if (animal instanceof Dog) { |
|||
((Dog) animal).swim(); |
|||
} |
|||
} |
|||
|
|||
|
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,9 @@ |
|||
package w6; |
|||
|
|||
public class Cat extends Animal { |
|||
@Override |
|||
public void makeSound() { |
|||
System.out.println("喵喵喵"); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,13 @@ |
|||
package w6; |
|||
|
|||
public class Dog extends Animal implements Swimmable{ |
|||
@Override |
|||
public void makeSound() { |
|||
System.out.println("汪汪汪!"); |
|||
|
|||
} |
|||
@Override |
|||
public void swim() { |
|||
System.out.println("狗刨式游泳"); |
|||
} |
|||
} |
|||
@ -0,0 +1,5 @@ |
|||
package w6; |
|||
|
|||
public interface Swimmable { |
|||
void swim(); |
|||
} |
|||
|
After Width: | Height: | Size: 97 KiB |
Loading…
Reference in new issue