MST

星途 面试题库

面试题:Java多态在复杂项目中如何通过继承实现不同业务逻辑

假设在一个电商复杂项目中,有一个基础的商品类`Product`,有`displayInfo`方法用于展示商品信息。现有实体类`Book`和`Clothes`继承自`Product`,请分别重写`displayInfo`方法以展示图书的作者、书名等信息以及衣服的尺码、颜色等信息,并阐述在项目中这样使用多态有什么好处。
41.0万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

代码实现

  1. 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);
    }
}
  1. 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}")

多态的好处

  1. 代码的可维护性:当需要修改或添加新的商品类型时,只需要在对应的子类中进行修改或添加,而不需要修改大量的调用代码。例如,如果要添加一个Electronics类,只需要继承Product类并实现displayInfo方法,不会影响到BookClothes类及其调用代码。
  2. 代码的可扩展性:方便增加新的商品类型。在电商项目中可能会不断引入新的商品类别,使用多态可以轻松地添加新的子类,而不需要对已有代码结构进行大规模调整。
  3. 提高代码的灵活性:在处理商品展示逻辑时,可以使用Product类型的变量来引用不同子类的对象,根据实际对象的类型调用相应的displayInfo方法。例如,可以将不同的商品对象放入一个ListArray中,遍历这个集合并调用displayInfo方法,而不需要关心具体是哪种商品类型,这使得代码更加通用和灵活。