Java面向?qū)ο缶幊痰亩鄳B(tài)是指允許一個類的引用變量指向另一個類的對象,從而實(shí)現(xiàn)在運(yùn)行時(shí)根據(jù)實(shí)際類型調(diào)用相應(yīng)的方法。多態(tài)的實(shí)現(xiàn)主要依賴于繼承、接口和方法覆蓋。以下是多態(tài)的一些常見用法:
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");
}
}
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("The cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Dog();
myAnimal.makeSound(); // 輸出 "The dog barks"
myAnimal = new Cat();
myAnimal.makeSound(); // 輸出 "The cat meows"
}
}
interface Flyable {
void fly();
}
interface Swimmable {
void swim();
}
class Bird implements Flyable, Swimmable {
@Override
public void fly() {
System.out.println("The bird is flying");
}
@Override
public void swim() {
System.out.println("The bird is swimming");
}
}
public class Main {
public static void main(String[] args) {
Flyable myFlyable = new Bird();
myFlyable.fly(); // 輸出 "The bird is flying"
Swimmable mySwimmable = new Bird();
mySwimmable.swim(); // 輸出 "The bird is swimming"
}
}
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("The dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Dog();
myAnimal.makeSound(); // 輸出 "The dog barks"
}
}
instanceof
關(guān)鍵字檢查對象是否為子類的實(shí)例。class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("The dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Dog();
if (myAnimal instanceof Dog) {
Dog myDog = (Dog) myAnimal;
myDog.makeSound(); // 輸出 "The dog barks"
} else {
System.out.println("The animal is not a dog");
}
}
}
通過使用多態(tài),Java代碼更加靈活、可擴(kuò)展和易于維護(hù)。