设计抽象类Person,派生出具体类:学生类Student和教师类Teacher,创建若干不同类对象后并在主方法中测试。
数据成员定义:
Person [ID,姓名,生日]
Student [专业,成绩]
Teacher [职称,工资]
带参构造方法分别为:
Person(int id,String name, int bir)
Student(int id,String name, int bir, String major,double score)
Teacher(int id,String name, int bir, String title, double salary)
toString方法(Eclipse自动生成)
输入格式:
第一行整数n表示有n个对象,每个对象占2行,第一行为数字0(表示学生)或1(表示教师),第二行为生成对象的参数。
输出格式:
按行输出具体对象的信息。
输入样例:
在这里给出一组输入。例如:
5
0
10101 Peter 20010121 Computer 87.5
1
20110014 Crystal 19900103 AI 7000
0
10102 Rose 20010715 E-Commerce 90
1
20120019 David 19781218 Prof 12000
0
10103 Semon 20000405 Computer 88
输出样例:
在这里给出相应的输出。例如:
Student [id=10101, name=Peter, bir=20010121, major=Computer, score=87.5]
Teacher [id=20110014, name=Crystal, bir=19900103, title=AI, salary=7000.0]
Student [id=10102, name=Rose, bir=20010715, major=E-Commerce, score=90.0]
Teacher [id=20120019, name=David, bir=19781218, title=Prof, salary=12000.0]
Student [id=10103, name=Semon, bir=20000405, major=Computer, score=88.0]
解析
import java.util.Scanner;
abstract class Person {
public int id;
public String name;
public int bir;
public Person(int id, String name, int bir) {
this.id = id;
this.name = name;
this.bir = bir;
}
}
class Student extends Person{
public String major;
public double score;
public Student(int id, String name, int bir, String major, double score) {
super(id, name, bir);
this.major = major;
this.score = score;
}
@Override
public String toString() {
return "Student [" +
"id=" + id +
", name=" + name +
", bir=" + bir +
", major=" + major +
", score=" + score +
']';
}
}
class Teacher extends Person{
public String title;
public double salary;
public Teacher(int id, String name, int bir, String title, double salary) {
super(id, name, bir);
this.title = title;
this.salary = salary;
}
@Override
public String toString() {
return "Teacher [" +
"id=" + id +
", name=" + name +
", bir=" + bir +
", title=" + title +
", salary=" + salary +
']';
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int n= scanner.nextInt();
for (int i = 0; i <n ; i++) {
int a= scanner.nextInt();
int b= scanner.nextInt();
String name= scanner.next();
int bir= scanner.nextInt();
String major= scanner.next();
double score= scanner.nextDouble();
if(a==0){
Student student=new Student(b,name,bir,major,score);
System.out.println(student);
}
else {
Teacher teacher=new Teacher(b,name,bir,major,score);
System.out.println(teacher);
}
}
}
}