Java多態(tài)性是通過(guò)繼承、接口和方法重寫(xiě)實(shí)現(xiàn)的。多態(tài)性允許我們使用一個(gè)共同的接口表示不同類型的對(duì)象,從而在運(yùn)行時(shí)根據(jù)對(duì)象的實(shí)際類型調(diào)用相應(yīng)的方法。這是通過(guò)編譯器在運(yùn)行時(shí)解析方法調(diào)用的實(shí)現(xiàn)的。
以下是Java多態(tài)性的實(shí)現(xiàn)方式:
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("The dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Dog(); // 使用父類引用指向子類對(duì)象
myAnimal.makeSound(); // 輸出 "The dog barks"
}
}
interface Flyable {
void fly();
}
class Bird implements Flyable {
@Override
public void fly() {
System.out.println("The bird is flying");
}
}
class Airplane implements Flyable {
@Override
public void fly() {
System.out.println("The airplane is flying");
}
}
public class Main {
public static void main(String[] args) {
Flyable myFlyable = new Bird(); // 使用接口引用指向?qū)崿F(xiàn)類對(duì)象
myFlyable.fly(); // 輸出 "The bird is flying"
myFlyable = new Airplane(); // 使用相同的接口引用指向另一個(gè)實(shí)現(xiàn)類對(duì)象
myFlyable.fly(); // 輸出 "The airplane is flying"
}
}
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("The dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Dog(); // 使用父類引用指向子類對(duì)象
myAnimal.makeSound(); // 輸出 "The dog barks"
}
}
通過(guò)這些方式,Java多態(tài)性允許我們編寫(xiě)更加靈活和可擴(kuò)展的代碼。