创建人类Preson,在以该类为父类创建一个学生子类Student,子类成员包括从父类继承来的成员和新增成员两部分,每部分包括数据成员和成员函数,再定义一个测试类TestStudent输出Student类的信息,生成Java
时间: 2024-05-14 13:14:41 浏览: 90
Java创建一个类-类名称student
代码如下:
```
// 定义人类
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void introduce() {
System.out.println("I am a person. My name is " + name + ", and I am " + age + " years old.");
}
}
// 定义学生类
class Student extends Person {
private String school;
private String grade;
public Student(String name, int age, String school, String grade) {
super(name, age);
this.school = school;
this.grade = grade;
}
public String getSchool() {
return school;
}
public String getGrade() {
return grade;
}
public void setSchool(String school) {
this.school = school;
}
public void setGrade(String grade) {
this.grade = grade;
}
public void study() {
System.out.println("I am a student. I am studying in " + school + ", and my grade is " + grade + ".");
}
}
// 定义测试类
class TestStudent {
public static void main(String[] args) {
Student s = new Student("Tom", 18, "ABC High School", "Grade 12");
s.introduce();
s.study();
}
}
```
以上代码中,Person类为父类,Student类为子类,TestStudent类为测试类。在Student类中,新增了school和grade两个成员变量,以及study()方法。在TestStudent类中,创建了一个Student对象s,并调用其introduce()和study()方法,输出其信息。
阅读全文