实现Java简单继承
Posted 进击的巨人
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实现Java简单继承相关的知识,希望对你有一定的参考价值。
面向对象练习-简单继承
一、完成教师类的创建
说明:
id 代表身份证号
name 表示姓名
birth 表示出生日期
title 表示职称(讲师,副教授,教授等)
二、完成学生类的创建
说明:
major 代表专业
三、编写主类测试
四、使用继承的方法来实现类之间的关系设计。
代码实现:
1 class Person{ 2 String id,name,birth; 3 public Person() { 4 } 5 public Person(String id,String name,String birth) { 6 this.id=id; 7 this.name=name; 8 this.birth=birth; 9 } 10 public void setId(String id) { 11 this.id = id; 12 } 13 public void setName(String name) { 14 this.name = name; 15 } 16 public void setBirth(String birth) { 17 this.birth = birth; 18 } 19 public String getBirth() { 20 return birth; 21 } 22 public String getId() { 23 return id; 24 } 25 public String getName() { 26 return name; 27 } 28 public void showInfo() { 29 System.out.printf("name is: %s ,id is: %s ,birth is: %s,",name,id,birth); 30 } 31 } 32 class Student extends Person{ 33 String major; 34 public Student() { 35 36 } 37 public Student(String id,String name,String birth,String major) { 38 super(id, name, birth); 39 this.major=major; 40 } 41 public void setMajor(String major) { 42 this.major = major; 43 } 44 public String getMajor() { 45 return major; 46 } 47 @Override 48 public void showInfo() { 49 super.showInfo(); 50 System.out.println("major is : "+major); 51 } 52 } 53 class Teacher extends Person{ 54 String title; 55 public Teacher() { 56 } 57 public Teacher(String id,String name,String birth,String title) { 58 super(id, name, birth); 59 this.title=title; 60 } 61 public void setTitle(String title) { 62 this.title = title; 63 } 64 public String getTitle() { 65 return title; 66 } 67 @Override 68 public void showInfo() { 69 super.showInfo(); 70 System.out.println("title is : "+title); 71 } 72 } 73 public class Main{ 74 75 public static void main(String[] args) { 76 Student stu=new Student("1000","张大","1998.01.23","Computer"); 77 Student stu1=new Student(); 78 stu1.setName("张三"); 79 stu1.setBirth("1998.04.01"); 80 stu1.setId("1001"); 81 stu1.setMajor("Computer"); 82 83 Teacher teacher1=new Teacher("ls1001","李大","1977.01.01","Professor"); 84 Teacher teacher=new Teacher(); 85 teacher.setName("李四"); 86 teacher.setBirth("1974.05.01"); 87 teacher.setId("ls1002"); 88 teacher.setTitle("Professor"); 89 90 stu.showInfo(); 91 stu1.showInfo(); 92 teacher1.showInfo(); 93 teacher.showInfo(); 94 } 95 96 }
以上是关于实现Java简单继承的主要内容,如果未能解决你的问题,请参考以下文章