Junior — Middle
How to rewrite a class definition with an interface to enable polymorphic behavior?
sobes.tech AI
Answer from AI
To ensure polymorphic behavior when implementing a class with an interface in Java, you need to:
- Define an interface with the necessary methods.
- Create a class that implements this interface and implement all its methods.
- Use variables of the interface type to store objects of classes that implement this interface.
Example:
// Interface
public interface Animal {
void makeSound();
}
// Class implementing the interface
public class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
public class Cat implements Animal {
@Override
public void makeSound() {
System.out.println("Meow!");
}
}
// Using polymorphism
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.makeSound(); // Outputs: Woof!
myCat.makeSound(); // Outputs: Meow!
}
}
Thus, objects of different classes can be handled through a common interface, which provides polymorphism.