实验三—根据派生类写出基类

class People{
protected String id;
protected String name;

/** 你提交的代码将被嵌在这里(替换此行) **/

}

class Student extends People{
protected String sid;
protected int score;
public Student() {
name = “Pintia Student”;
}
public Student(String id, String name, String sid, int score) {
super(id, name);
this.sid = sid;
this.score = score;
}
public void say() {
System.out.println(“I’m a student. My name is ” + this.name + “.”);
}

}
public class Main {
public static void main(String[] args) {
Student zs = new Student();
zs.setId(“370211X”);
zs.setName(“Zhang San”);
zs.say();
System.out.println(zs.getId() + ” , ” + zs.getName());

    Student ls = new Student("330106","Li Si","20183001007",98);
    ls.say();
    System.out.println(ls.getId() + " : " + ls.getName());

    People ww = new Student();
    ww.setName("Wang Wu");
    ww.say();

    People zl = new People("370202", "Zhao Liu");
    zl.say();
}

}

看题目,我们只需要补充部分代码。先观察主函数因为主函数有setter和getter方法所以需要在前面构造。还有say方法,相当于tostring方法,观察输出I’m a person! My name is Zhao Liu.,类似于子类student的say方法输出只需要改一下输出内容就可、

除此之外还需要调用构造函数,观察子类既需要无参也需要有参方法,有参里面传参的是id和name

子类如下

public Student() {

name = “Pintia Student”; }

public Student(String id, String name, String sid, int score){

super(id, name); this.sid = sid; this.score = score;

}

总代码如下

class People {
protected String id;
protected String name;
public People() {

}
public People(String id, String name) {
    this.id = id;
    this.name = name;
}   
public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public void say() {
    System.out.println("I'm a person! My name is " + this.name + ".");
}

}

发表评论

蜀ICP备2022010829号