一、简单继承关系实例
1.1.创建一个Person类,属性有编号(id)、姓名(name)、职位(job),带三个参数构造方法。
方法:登入login()、注册register()、自我介绍talk()。
public class Person{
protected String id;
protected String name;
protected String job;
public Person(String id,String name,String job){
this.id=id;
this.job=job;
this.name=name;
}
public void login(){
System.out.println("登入");
}
public void register(){
System.out.println("注册");
}
public void talk(){
System.out.println("自我介绍");
}
}
1.2.创建一个Student类继承Person类,属性:学费(money),方法:test()考试
public class Student extends Person{
protected double money;
public Student(String id, String name, String job,double money) {
super(id, name, job);
this.money=money;
}
public void test(){
System.out.println("考试");
}
@Override
public void talk(){
System.out.println("学生:编号-"+id+" 姓名-"+name+" 职位-"+job+" 学费-"+money);
}
}
1.3.创建一个Teacher类继承Person类,属性:工作(salary)、方法:work()工作
class Teacher extends Person{
private double salary;
public Teacher(String id, String name, String job,double salary) {
super(id, name, job);
this.salary=salary;
}
public void work(){
System.out.println("工作");
}
public void talk(){
System.out.println("学生:编号-"+id+" 姓名-"+name+" 职位-"+job+" 工作-"+salary);
}
}
1.4.创建一个测试类TestPerson
public class TestPerson {
public static void main(String[] args){
Student student=new Student("S001","张三","学生",9999);
Teacher teacher=new Teacher("T001","李四","老师",12000);
student.talk();
student.test();
teacher.talk();
teacher.work();
}
}
运行结果: