面向对象编程的核心特性与抽象类应用
1. 多态简化代码维护
在编程中,多态是一个强大的特性,它能极大地简化代码维护。为了理解多态的优势,我们先看看在不支持多态的编程语言中,处理不同类型对象的方式。
1.1 无多态时的处理方式
在没有多态的情况下,通常会使用一系列的 if 测试来处理不同类型的学生对象,示例代码如下:
for (Student s : studentBody) {
// Process the next student.
// Pseudocode.
if (s is an undergraduate student)
s.printAsUndergraduateStudent();
else if (s is a graduate student)
s.printAsGraduateStudent();
else if ...
}
随着情况的增多,代码会变得像“意大利面”一样复杂。而且,这种 if 测试会在应用程序的无数地方出现,只要是遍历包含不同类型学生的集合时就会用到。
1.2 多态的处理方式
而使用多态时,代码会变得简洁很多。以下是多态遍历学生集合的示例:
// Step through the ArrayList (collection) ...
for (Student s : stud
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



