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代码更加灵活、可扩展和易于维护。