5 changed files with 46 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("Meow!"); |
||||
|
} |
||||
|
} |
||||
@ -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"); |
||||
|
} |
||||
|
} |
||||
@ -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"); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,3 @@ |
|||||
|
public interface Swimmable { |
||||
|
void swim(); |
||||
|
} |
||||
Loading…
Reference in new issue