主要实现:
(1)类的声明方法
(2)this关键字的作用
(3)super关键字的作用
(4)类的继承
(5)方法重写
废话太多了,看代码
Student.java和StudentInfo.java位于同一个包下
//Student.java
public class Student {
int num;
String name;
double mathScore;
double computerScore;
Student(int num,String name,double mathScore,double computerScore){
this.num= num;
this.name= name;
this.mathScore= mathScore;
this.computerScore= computerScore;
}
void setNum(int num) {
this.num=num;
}
int getNum() {
return this.num;
}
void setName(String name) {
this.name=name;
}
String getName() {
return this.name;
}
void setMathScore(double mathScore) {
this.mathScore =mathScore;
}
double getMathScore()
{
return this.mathScore;
}
void setComputerScore(double computerScore) {
this.computerScore= computerScore;
}
double getComputerScore()
{
return this.computerScore;
}
double getScoreSum()
{
return this.computerScore+this.mathScore;
}
void print() {
System.out.println("学号:"+getNum()+",姓名:"+getName()+",数学:"+getMathScore()+",计算机:"+getComputerScore());
}
}
class PostGraduate extends Student{
String teacherName;
String resDirection;
PostGraduate(int num,String name,double mathScore,double computerScore,String teacherName,String resDirection){
super(num, name, mathScore, computerScore);
this.teacherName= teacherName;
this.resDirection =resDirection;
}
void setTeacherName(String teacherName) {
this.teacherName= teacherName;
}
void setResDirection(String resDirection){
this.resDirection= resDirection;
}
String getTeacherName() {
return this.teacherName;
}
String getResDirection() {
return resDirection;
}
void print() {
System.out.println("PostGraduate重写print方法,输出成员变量:\n"+getNum()+",\t"+getName()+",\t"+getMathScore()+",\t"+getComputerScore()+",\t"+getTeacherName()+",\t"+getResDirection());
}
}
//StudentInfo.java
import java.util.*;
public class StudentInfo{
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("输入学生的个数:");
int stuNum = reader.nextInt();
Student stu[] =new Student[stuNum];
for(int i=0;i<stu.length;i++)
{
System.out.println("请输入第"+(i+1)+"位学生学号,姓名,数学成绩,计算机成绩");
stu[i]=new Student(reader.nextInt(), reader.next(),reader.nextDouble(), reader.nextDouble());
}
System.out.println("学生信息为:");
for (Student i:stu)
{
i.print();
}
for(int i =0;i < stuNum-1;i++)//共比较stuNum趟,每一趟选出最大的数
for(int j =0;j<stuNum-i-1;j++)//每一趟比较stuNum-i-1次
{
if(stu[j].getScoreSum()<stu[j+1].getScoreSum())
{
Student temp;
temp =stu[j+1];
stu[j+1]=stu[j];
stu[j]=temp;
}
}
System.out.println("学生信息按成绩由高到低排序为:");
for (Student i:stu)
{
i.print();
}
}
}
运行结果: