Browse Source

Add w6 folder with animal sound system

main
范馨遥 1 day ago
parent
commit
ba1ca63b82
  1. 3
      w6/Animal.java
  2. 6
      w6/Cat.java
  3. 11
      w6/Dog.java
  4. 23
      w6/Main.java
  5. 3
      w6/Swimmable.java

3
w6/Animal.java

@ -0,0 +1,3 @@
public abstract class Animal {
public abstract void makeSound();
}

6
w6/Cat.java

@ -0,0 +1,6 @@
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow!");
}
}

11
w6/Dog.java

@ -0,0 +1,11 @@
public class Dog extends Animal implements Swimmable {
@Override
public void makeSound() {
System.out.println("Woof!");
}
@Override
public void swim() {
System.out.println("Dog is swimming");
}
}

23
w6/Main.java

@ -0,0 +1,23 @@
public class Main {
public static void main(String[] args) {
// Test polymorphism with Animal references
Animal dog = new Dog();
Animal cat = new Cat();
System.out.println("Testing makeSound():");
dog.makeSound(); // Should output "Woof!"
cat.makeSound(); // Should output "Meow!"
// Test swim() method for Dog
System.out.println("\nTesting swim():");
if (dog instanceof Swimmable) {
Swimmable swimmableDog = (Swimmable) dog;
swimmableDog.swim(); // Should output "Dog is swimming"
}
// Test that Cat doesn't implement Swimmable
if (!(cat instanceof Swimmable)) {
System.out.println("Cat cannot swim");
}
}
}

3
w6/Swimmable.java

@ -0,0 +1,3 @@
public interface Swimmable {
void swim();
}
Loading…
Cancel
Save