在Java中,多态允许我们使用一个接口或父类引用指向子类对象,从而实现通用的代码。为了实现这一目标,我们可以采用以下方法:
// 定义一个接口 interface Animal { void makeSound(); } // 定义一个抽象类 abstract class Mammal { abstract void makeSound(); } // 定义子类 class Dog extends Mammal implements Animal { @Override public void makeSound() { System.out.println("Woof!"); } } class Cat extends Mammal implements Animal { @Override public void makeSound() { System.out.println("Meow!"); } } public class Main { public static void main(String[] args) { Animal myAnimal = new Dog(); myAnimal.makeSound(); // 输出 "Woof!" myAnimal = new Cat(); myAnimal.makeSound(); // 输出 "Meow!" } }
class Box<T> { private T content; public void setContent(T content) { this.content = content; } public T getContent() { return content; } } public class Main { public static void main(String[] args) { Box<Integer> intBox = new Box<>(); intBox.setContent(42); System.out.println(intBox.getContent()); // 输出 42 Box<String> strBox = new Box<>(); strBox.setContent("Hello, World!"); System.out.println(strBox.getContent()); // 输出 "Hello, World!" } }
interface AnimalFactory { Animal createAnimal(); } class DogFactory implements AnimalFactory { @Override public Animal createAnimal() { return new Dog(); } } class CatFactory implements AnimalFactory { @Override public Animal createAnimal() { return new Cat(); } } public class Main { public static void main(String[] args) { AnimalFactory myFactory = new DogFactory(); Animal myAnimal = myFactory.createAnimal(); myAnimal.makeSound(); // 输出 "Woof!" myFactory = new CatFactory(); myAnimal = myFactory.createAnimal(); myAnimal.makeSound(); // 输出 "Meow!" } }
通过以上方法,我们可以在Java中编写通用的代码,实现多态。