要求:根据不同学生的等级进行不同的分数成绩评定
1、封装
1、封装的概念
。。。
package bao;
abstract class Student {
final static int CourseNo = 3;// 课程
String name;// 姓名
String type; // 类型
int[] courses;// 成绩的数组
String courseGrade;// 等级
public Student(String name) {
this.name = name;
courses = new int[CourseNo];
courseGrade = " ";// 初始成绩等级为空字符
}
public abstract void calculateGrade();// 计算总成绩的抽象方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void setCourseScore(int courseNumber, int courseScore) {
courses[courseNumber] = courseScore; // 按课程索引号设置课程的成绩
}
public int getCourseScore(int courseNumber) {
return courses[courseNumber];
}
public void setCourseGrade(String courseGrade) {
this.courseGrade = courseGrade;
}
public String getCourseGrade() {
return courseGrade;
}
}
2、继承
接口:。。。
抽象类:。。。
2.1、本科生继承学生类
package bao;
class Undergraduate extends Student {
public Undergraduate(String name) { // 构造方法
super(name); // 使用super调用父类的构造方法
type = "本科生"; // 初始化父类的属性
}
@Override
public void calculateGrade() { // 实现父类的抽象方法
int total = 0;
double average = 0;
for (int i = 0; i < CourseNo; i++) { // 所有课程的成绩总和
total += courses[i];
}
average = total / CourseNo; // 计算平均成绩
if (average >= 90 && average < 100)
courseGrade = "优秀";
else if (average >= 80 && average < 90)
courseGrade = "良好";
else if (average >= 70 && average < 80)
courseGrade = "一般";
else if (average >= 60 && average < 70)
courseGrade = "及格";
else
courseGrade = "不及格";
}
}
2.2、 研究生继承学生类
package bao;
class Postgraduate extends Student {
public Postgraduate(String name) {
super(name);
type = "研究生";
}
public void calculateGrade() { // 实现父类的抽象方法
int total = 0;
double average = 0;
for (int i = 0; i < CourseNo; i++) { // 所有课程的成绩总和
total += courses[i];
}
average = total / CourseNo; // 计算平均成绩
if (average >= 95 && average < 100)
courseGrade = "优秀";
else if (average >= 85 && average < 95)
courseGrade = "良好";
else if (average >= 75 && average < 85)
courseGrade = "一般";
else if (average >= 65 && average < 75)
courseGrade = "及格";
else
courseGrade = "不及格";
}
}
3、多态
多态的概念:。。。
package bao;
public class Polymorphism {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student[] students = new Student[5];
// 父类引用子类的对象
students[0] = new Undergraduate("张三");
students[1] = new Undergraduate("赵薇");
students[2] = new Postgraduate("李四");
students[3] = new Undergraduate("杨密");
students[4] = new Postgraduate("唐洋");
for (int i = 0; i < 5; i++) {
students[i].setCourseScore(0, 88);
students[i].setCourseScore(1, 90);
students[i].setCourseScore(2, 96);
}
for (int i = 0; i < 5; i++) {
students[i].calculateGrade();// 调用各自类中的方法
}
System.out.println("姓名 " + " 类型" + " 成绩");
System.out.println("--------------------------------------------");
for (int i = 0; i < 5; i++) {
System.out
.println(students[i].getName() + " " + students[i].getType() + " " + students[i].getCourseGrade());
}
}
}