返回

OOP的指引下寻找全班总分最高的那颗星

后端

OOP 编程的哲学与实践

面向对象编程 (OOP) 是一种编程范式,它使用“对象”来设计应用程序和计算机程序。这些“对象”可以被视为现实世界中事物的抽象,它们具有属性和行为。OOP 是将代码组织成易于维护和重用的结构的一种好方法。

OOP 编程的四大核心原则:

  • 抽象(Abstraction): 关注对象的特征和功能,忽略其内部实现细节。
  • 封装(Encapsulation): 将对象的数据和行为绑定在一起,以保护其免受外界干扰。
  • 继承(Inheritance): 允许子类继承父类的属性和行为,从而实现代码的重用。
  • 多态性(Polymorphism): 允许子类以不同的方式实现父类的方法,从而实现代码的灵活性。

面向对象编程的优点:

  • 代码复用性: 允许重复使用代码,减少开发时间和成本。
  • 可维护性: 使代码更易于维护和扩展。
  • 可扩展性: 使代码更易于扩展和重用。
  • 安全性: 通过封装和访问控制,提高代码的安全性。

OOP 找到总分最高学生大作战

建立学生类

public class Student {
    private String name;
    private int[] scores;

    public Student(String name, int[] scores) {
        this.name = name;
        this.scores = scores;
    }

    public String getName() {
        return name;
    }

    public int[] getScores() {
        return scores;
    }

    public int getTotalScore() {
        int totalScore = 0;
        for (int score : scores) {
            totalScore += score;
        }
        return totalScore;
    }
}

建立班级类

public class Classroom {
    private Student[] students;

    public Classroom(Student[] students) {
        this.students = students;
    }

    public Student findStudentWithHighestTotalScore() {
        Student highestScoringStudent = students[0];
        for (int i = 1; i < students.length; i++) {
            if (students[i].getTotalScore() > highestScoringStudent.getTotalScore()) {
                highestScoringStudent = students[i];
            }
        }
        return highestScoringStudent;
    }
}

测试代码

public class Main {
    public static void main(String[] args) {
        Student[] students = {
            new Student("Alice", new int[]{90, 85, 95}),
            new Student("Bob", new int[]{75, 80, 90}),
            new Student("Carol", new int[]{80, 85, 90}),
            new Student("Dave", new int[]{95, 90, 95})
        };

        Classroom classroom = new Classroom(students);
        Student highestScoringStudent = classroom.findStudentWithHighestTotalScore();

        System.out.println("The student with the highest total score is: " + highestScoringStudent.getName());
    }
}

总结

运用面向对象编程,我们轻而易举地找到了我们所需要的总分最高的学生的信息,这种技术使得我们的代码可读性大大提高了,维护起来也更加简单。