Java面向對象編程的多態是指允許一個類的引用變量指向另一個類的對象,從而實現在運行時根據實際類型調用相應的方法。多態的實現主要依賴于繼承、接口和方法覆蓋。以下是多態的一些常見用法:
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
關鍵字檢查對象是否為子類的實例。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");
}
}
}
通過使用多態,Java代碼更加靈活、可擴展和易于維護。