在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中編寫通用的代碼,實現多態。