package cn.exp; //都是比较常见和标准的写法。注意eclipse工具的使用。 class AgeException extends RuntimeException{ public AgeException(String Message) { super(Message); } } class Person{ String name; String gender; int age; public Person(String name, String gender, int age) { //super(); if(age<=0){ throw new AgeException("年龄错误,请重新输入"); } this.name = name; this.gender = gender; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person [name=" + name + ", gender=" + gender + ", age=" + age+ "]"; } } class Student extends Person{ int id; public Student(String name, String gender, int age, int id) { super(name, gender, age); if(age<=0){ throw new AgeException("年龄错误,请重新输入"); } this.id = id; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public String toString() { return "Student [name=" + name + ", gender=" + gender + ", age=" + age + ",id="+id+"]"; } public void show(){ System.out.println("学生爱学习"); } } class Teacher extends Person{ int pid; public Teacher(String name, String gender, int age, int pid) { super(name, gender, age); if(age<=0){ throw new AgeException("年龄错误,请重新输入"); } this.pid = pid; } public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public String toString(){ return "Teacher [name=" + name + ", gender=" + gender + ", age=" + age + ",pid="+pid+"]"; } public void show(){ System.out.println("老师爱吃饭"); } } public class PersonTest1 { public static void main(String[] args) { Student student=new Student("小米", "女", 12, 77); student.show(); System.out.println(student.toString()); Teacher teacher=new Teacher("小兰", "男", 77, 88); teacher.show(); System.out.println(teacher.toString()); } }
时间: 2024-11-25 18:12:47