代码实现
- Java示例
class Product {
public void displayInfo() {
System.out.println("这是一个商品");
}
}
class Book extends Product {
private String author;
private String title;
public Book(String author, String title) {
this.author = author;
this.title = title;
}
@Override
public void displayInfo() {
System.out.println("图书信息:作者 " + author + ",书名 " + title);
}
}
class Clothes extends Product {
private String size;
private String color;
public Clothes(String size, String color) {
this.size = size;
this.color = color;
}
@Override
public void displayInfo() {
System.out.println("衣服信息:尺码 " + size + ",颜色 " + color);
}
}
- Python示例
class Product:
def displayInfo(self):
print("这是一个商品")
class Book(Product):
def __init__(self, author, title):
self.author = author
self.title = title
def displayInfo(self):
print(f"图书信息:作者 {self.author},书名 {self.title}")
class Clothes(Product):
def __init__(self, size, color):
self.size = size
self.color = color
def displayInfo(self):
print(f"衣服信息:尺码 {self.size},颜色 {self.color}")
多态的好处
- 代码的可维护性:当需要修改或添加新的商品类型时,只需要在对应的子类中进行修改或添加,而不需要修改大量的调用代码。例如,如果要添加一个
Electronics
类,只需要继承Product
类并实现displayInfo
方法,不会影响到Book
和Clothes
类及其调用代码。
- 代码的可扩展性:方便增加新的商品类型。在电商项目中可能会不断引入新的商品类别,使用多态可以轻松地添加新的子类,而不需要对已有代码结构进行大规模调整。
- 提高代码的灵活性:在处理商品展示逻辑时,可以使用
Product
类型的变量来引用不同子类的对象,根据实际对象的类型调用相应的displayInfo
方法。例如,可以将不同的商品对象放入一个List
或Array
中,遍历这个集合并调用displayInfo
方法,而不需要关心具体是哪种商品类型,这使得代码更加通用和灵活。