java 如何实现多态
多态的实现方式
在Java中,多态主要通过继承、接口和方法重写实现。以下是具体实现方法:
继承与方法重写 子类继承父类并重写父类方法,通过父类引用指向子类对象实现多态。
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Dog(); // 父类引用指向子类对象
myAnimal.sound(); // 输出: Dog barks
}
}
接口实现 通过接口定义方法,不同类实现相同接口但提供不同实现。
interface Shape {
void draw();
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing Circle");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println("Drawing Square");
}
}
public class Main {
public static void main(String[] args) {
Shape shape1 = new Circle();
Shape shape2 = new Square();
shape1.draw(); // 输出: Drawing Circle
shape2.draw(); // 输出: Drawing Square
}
}
方法重载 在同一个类中,多个方法同名但参数列表不同,编译时根据参数决定调用哪个方法。
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(5, 3)); // 输出: 8
System.out.println(calc.add(2.5, 3.5)); // 输出: 6.0
}
}
多态的核心要点
- 运行时绑定:通过父类引用调用子类重写方法时,JVM在运行时确定实际调用的方法。
- 向上转型:子类对象赋值给父类引用变量是安全的,反之需要强制类型转换。
- instanceof操作符:用于检查对象是否为特定类的实例,避免类型转换异常。
Animal animal = new Dog();
if (animal instanceof Dog) {
Dog dog = (Dog) animal; // 安全向下转型
}
多态提高了代码的可扩展性和可维护性,允许在不修改现有代码的情况下添加新功能。







