题目描述
编写Person类
包含成员方法: String name; int age;
包含成员变量: show();
构造方法: Person(String name, int age);
=========================================
编写Student类(继承Person类)
包含构造方法: Student (String dep, String name, int age)
包含成员变量: String department;
Main类已经编写好。
import java.util.*; public class Main { public static void main(String[] args) { Scanner r = new Scanner(System.in); String dep; String name; int age; dep = r.next(); name = r.next(); if( !r.hasNextInt() ) return; age = r.nextInt(); if( age < 0 ) return; Person stu1=new Student(dep,name,age); stu1.show(); } }
输入
输入院系名字、学生姓名、年龄
输出
输出详见样例
样例输入
Computer Obama 42
样例输出
called the constructor of Person class I am a student from the department of Computer called the constructor of Student class: Student(String name,int age,String dep) Name:Obama Age: 42
代码:
class Person{
protected String name;
protected int age;
public Person() {
System.out.println("called the constructor of Person class");
}
public Person(String name, int age) {
this();
this.name = name;
this.age = age;
}
public void show() {
System.out.println("Name:"+name+" Age: "+age);
}
}
class Student extends Person{
private String department;
public Student (String dep, String name, int age) {
super(name,age);
this.department = dep;
System.out.println("I am a student from the department of "+department);
System.out.println("called the constructor of Student class: Student(String name,int age,String dep)");
}
}