1.定义Person类,要求如下:(1)成员变量包括姓名name,其为静态公有属性;(2)成员方法包括:working(String informatior 2.定义Student类继承Person,要求如下:(1)成员变量包括年龄,要求到装年龄属性不能小于0,当输错时提示“Age cannot b se(String course)表示学生选修某门课程course 重写父类方法working(String information 表示学生正在学习某个内容。 3、定义测试类 要求如下:定义Student类
时间: 2024-04-24 16:22:06 浏览: 100
以下是Java语言的代码实现:
```
public class Person {
public static String name;
public void working(String information) {
System.out.println(name + " is working on " + information);
}
}
public class Student extends Person {
private int age;
public void setAge(int age) {
if (age < 0) {
System.out.println("Age cannot be negative!");
} else {
this.age = age;
}
}
@Override
public void working(String information) {
System.out.println(name + " is studying " + information);
}
public void chooseCourse(String course) {
System.out.println(name + " is choosing the course: " + course);
}
}
public class Test {
public static void main(String[] args) {
Student student = new Student();
student.setAge(-1); // Age cannot be negative!
student.setAge(18);
student.chooseCourse("Java programming");
student.working("Object-Oriented Programming");
}
}
```
在测试类中,我们创建了一个Student对象,并设置其年龄为-1,会提示Age cannot be negative!;然后设置其年龄为18,调用了其选择课程和工作的方法,输出结果如下:
```
Age cannot be negative!
Jack is choosing the course: Java programming
Jack is studying Object-Oriented Programming
```
阅读全文