创建一个基类Person,属性有name和age,方法有显示个人信息printInfo()。如下所示: class Person{ int age; String name; void printInfo(){ System.out.println("姓名:"+name+",年龄:"+age); } } 派生类Teacher继承基类Person,包含teacherID属性,请重写printInfo ()。要求从键盘获取用户输入,并创建Teacher类对象并调
时间: 2024-01-08 21:03:03 浏览: 121
用printInfo()方法打印出教师的信息,代码如下:
```
import java.util.Scanner;
class Person {
int age;
String name;
void printInfo() {
System.out.println("姓名:" + name + ",年龄:" + age);
}
}
class Teacher extends Person {
int teacherID;
@Override
void printInfo() {
System.out.println("教师ID:" + teacherID + ",姓名:" + name + ",年龄:" + age);
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Teacher t = new Teacher();
System.out.println("请输入教师姓名:");
t.name = sc.nextLine();
System.out.println("请输入教师年龄:");
t.age = sc.nextInt();
System.out.println("请输入教师ID:");
t.teacherID = sc.nextInt();
t.printInfo();
}
}
```
运行结果如下:
```
请输入教师姓名:
张三
请输入教师年龄:
30
请输入教师ID:
123
教师ID:123,姓名:张三,年龄:30
```
阅读全文