多态是面向对象程序设计中的一个重要概念,它允许使用父类类型的引用来引用子类对象。在 Java 中,多态通过继承和方法重写来实现。
下面是一个示例代码:
class Animal {
public void makeSound() {
System.out.println("Animal is making a sound");
}
}
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow!");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
public class Main {
public static void main(String[] args) {
Animal animal1 = new Cat();
Animal animal2 = new Dog();
animal1.makeSound(); // 输出:Meow!
animal2.makeSound(); // 输出:Woof!
}
}
在上面的代码中,有一个 Animal
类以及它的两个子类 Cat
和 Dog
。每个类都有一个 makeSound()
方法,但实现的行为不同。
在 Main
类的 main()
方法中,我们创建了一个 Animal
类型的引用变量 animal1
和 animal2
,分别指向 Cat
类型的对象和 Dog
类型的对象。这里使用了多态的特性,子类对象赋值给了父类的引用。
当调用 animal1.makeSound()
时,实际上会执行 Cat
类中重写的 makeSound()
方法,输出 "Meow!"。
当调用 animal2.makeSound()
时,实际上会执行 Dog
类中重写的 makeSound()
方法,输出 "Woof!"。
这就是多态的效果:通过父类类型的引用来访问子类对象,并根据对象的实际类型确定调用哪个类的方法。这样可以增加代码的灵活性和可扩展性,使得代码具备更好的可维护性和可扩展性。
来看另一个示例代码:
class Parent {
int a = 100;
public int f() {
return 10;
}
}
class Son extends Parent {
int a = 200;
public int f() {
return 20;
}
public static void main(String[] args) {
Parent parent = new Son();
System.out.println(parent.f() + " " + parent.a);
}
}
这段代码的输出是 "20 100"。
代码中定义了两个类:Parent
和 Son
。Son
类是 Parent
类的子类,继承了 Parent
类的成员变量和方法。
在 main
方法中,创建了一个 Parent
类型的对象 parent
,但实际上是通过 new Son()
创建的。这是因为多态的特性,子类对象可以赋值给父类引用。
接下来,调用 parent.f()
方法。由于多态的特性,实际上会调用 Son
类中的 f()
方法。Son
类中的 f()
方法返回值为 20。
然后,通过 parent.a
访问成员变量 a
。由于成员变量不具有多态性,访问的是 Parent
类中的成员变量 a
,其值为 100。
最后,使用 System.out.println()
方法打印输出结果,将 parent.f()
的返回值和 parent.a
的值连接起来,输出为 "20 100"。