0%

【Java】类的继承实验:Student类


11.24新增抛出异常练习

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package Exception;

import java.util.Scanner;

public class Program {
public static void main(String[] args)
{
Student student=new Student();//实例化一个学生对象
String name,dep;
int age;//声明三个必要变量,为传入函数值做准备
Scanner scanner=new Scanner(System.in);//声明一个得到用户输入文字的功能对象
System.out.println("请输入学生姓名:");//提示语
name=scanner.next();//得到用户输入的一段字符串,并将其赋给name
System.out.println("请输入学生年龄:");
age=scanner.nextInt();//得到用户输入的一段整形数字,并将其赋给age
System.out.println("请输入学生院系:");
dep=scanner.next();

student.setNameAgeDep(name,age,dep);//调用函数设置学生的信息
student.show();//调用函数显示学生信息
System.out.println(student);//直接打印出学生对象(隐式调用toString函数)
Student student2=new Student();//设置第二个学生对象用户比对学生姓名
student2.setNameAgeDep("AAA",20,"Information");//设置第二个学生的信息
if(student.equals(student2))System.out.println("学生重名");
else System.out.println("学生不重名");//比较学生是否重名
}
}

//人“类”
class Person
{
//包含字段姓名与年龄
private String name;
private int age;

//设置姓名与年龄的访问器,如不需要重写toString与equals函数则不需要设置
//应尽量避免对父类的改动
public String getName()
{
return name;
}
public int getAge()
{
return age;
}

//显示目前类的调用情况
public Person()
{
System.out.println("调用了个人构造方法Person()");
}

//设置人“类”的姓名与年龄
public void SetNameAge(String name,int age)throws AgeException
{
this.name=name;
if(age<=0age>=25)throw new AgeException();
//设置学生年龄不得小于0,或大于25。若超过此值,则抛出异常。以下赋值语句将失效。
this.age=age;
}

//显示人“类”的姓名与年龄
public void show()
{
System.out.println("姓名:"+name+",年龄:"+age);
}
}

//学生类,继承自人“类”
class Student extends Person
{
//派生类新字段:院系
private String dep;

//设置学生的名字、年龄、所在院系
public void setNameAgeDep(String name,int age,String dep)
{
try
{
super.SetNameAge(name,age);
}
catch (AgeException e)
{
System.out.println("\nYou type a worng age info.\n");
}//捕获异常AgeException,并提示用户输入错误。
this.dep=dep;
}

//提示调用类的情况
public Student()
{
System.out.println("也调用了学生构造方法Student()");
}

//显示学生信息
public void show() {
super.show();
System.out.println("院系:" + dep);
}

//重写toString函数,使对象可被直接输出为字符串
public String toString()
{
return "学生姓名为"+getName()+",年龄为"+getAge()+",院系为"+dep+"。";
}

//重写equals函数,使之能比较学生姓名是否相等(即检测学生重名情况)
public boolean equals(Student student)
{
if(getName().equals(student.getName()))return true;
else return false;
}
}




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package Exception;

public class AgeException extends Exception{
public AgeException()
{
super();
}
public AgeException(String msg)
{
super(msg);
}
public AgeException(Throwable cause)
{
super(cause);
}
public AgeException(String msg,Throwable cause)
{
super (msg,cause);
}

}