引言
面向对象编程(OOP)中的多态是其中一个核心概念,它允许我们使用同一个接口调用不同的方法。掌握多态对于编写灵活、可扩展的代码至关重要。本文将提供一系列练习题,帮助你加深对多态的理解并提升相关技能。
练习题
练习题 1:动物分类
描述: 创建一个Animal基类,以及几个派生类如Dog、Cat和Bird。每个类都有一个makeSound方法。编写一个程序,创建一个Animal数组,并使用循环调用每个动物的makeSound方法。
代码示例:
class Animal {
public void makeSound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("Woof!");
}
}
class Cat extends Animal {
public void makeSound() {
System.out.println("Meow!");
}
}
class Bird extends Animal {
public void makeSound() {
System.out.println("Tweet!");
}
}
public class Main {
public static void main(String[] args) {
Animal[] animals = new Animal[4];
animals[0] = new Dog();
animals[1] = new Cat();
animals[2] = new Bird();
animals[3] = new Animal();
for (Animal animal : animals) {
animal.makeSound();
}
}
}
练习题 2:图形界面
描述: 创建一个Shape基类,以及几个派生类如Circle、Rectangle和Triangle。每个类都有一个draw方法。编写一个程序,创建一个Shape数组,并使用循环调用每个形状的draw方法。
代码示例:
class Shape {
public void draw() {
System.out.println("Drawing shape");
}
}
class Circle extends Shape {
public void draw() {
System.out.println("Drawing circle");
}
}
class Rectangle extends Shape {
public void draw() {
System.out.println("Drawing rectangle");
}
}
class Triangle extends Shape {
public void draw() {
System.out.println("Drawing triangle");
}
}
public class Main {
public static void main(String[] args) {
Shape[] shapes = new Shape[4];
shapes[0] = new Circle();
shapes[1] = new Rectangle();
shapes[2] = new Triangle();
shapes[3] = new Shape();
for (Shape shape : shapes) {
shape.draw();
}
}
}
练习题 3:车辆多态
描述: 创建一个Vehicle基类,以及几个派生类如Car、Truck和Bike。每个类都有一个startEngine方法。编写一个程序,创建一个Vehicle数组,并使用循环调用每个车辆的startEngine方法。
代码示例:
class Vehicle {
public void startEngine() {
System.out.println("Starting engine");
}
}
class Car extends Vehicle {
public void startEngine() {
System.out.println("Starting car engine");
}
}
class Truck extends Vehicle {
public void startEngine() {
System.out.println("Starting truck engine");
}
}
class Bike extends Vehicle {
public void startEngine() {
System.out.println("Starting bike engine");
}
}
public class Main {
public static void main(String[] args) {
Vehicle[] vehicles = new Vehicle[4];
vehicles[0] = new Car();
vehicles[1] = new Truck();
vehicles[2] = new Bike();
vehicles[3] = new Vehicle();
for (Vehicle vehicle : vehicles) {
vehicle.startEngine();
}
}
}
总结
通过以上练习题,你可以更好地理解面向对象编程中的多态概念。多态允许我们编写更加灵活和可扩展的代码,通过使用共同的接口来处理不同的对象。不断练习和尝试不同的场景,将有助于你更深入地掌握这一重要概念。
