Inheritance of Java classes: simple inheritance of Java and the difference between single inheritance and multi inheritance
•
Java
Simple inheritance
class class_name extends extend_class
{
//类的主体
}
public class Student extends Person{}
Example 1
public class People
{
public String name; //姓名
public int age; //年龄
public String sex; //性别
public String sn; //身份证号
public People(String name,int age,String sex,String sn)
{
this.name=name;
this.age=age;
this.sex=sex;
this.sn=sn;
}
public String toString()
{
return"姓名:"+name+"\n年龄:"+age+"\n性别:"+sex+"\n身份证号:"+sn;
}
}
public class Student extends People
{
private String stuNo; //学号
private String department; //所学专业
public Student(String name,String sn,String stuno,String department)
{
super(name,age,sex,sn); //调用父类中的构造方法
this.stuNo=stuno;
this.department=department;
}
public String toString()
{
return"姓名:"+name+"\n年龄:"+age+"\n性别:"+sex+"\n身份证号:"+sn+"\n学号:"+stuNo+"\n所学专业:"+department;
}
}
public class Teacher extends People
{
private int tYear; //教龄
private String tDept; //所教专业
public Teacher(String name,int tYear,String tDept)
{
super(name,sn); //调用父类中的构造方法
this.tYear=tYear;
this.tDept=tDept;
}
public String toString()
{
return"姓名:"+name+"\n年龄:"+age+"\n性别:"+sex+"\n身份证号:"+sn+"\n教龄:"+tYear+"\n所教专业:"+tDept;
}
}
public class PeopleTest
{
public static void main(String[] args)
{
//创建Student类对象
People stuPeople=new Student("王丽丽",23,"女","410521198902145589","00001","计算机应用与技术");
System.out.println("----------------学生信息---------------------");
System.out.println(stuPeople);
//创建Teacher类对象
People teaPeople=new Teacher("张文",30,"男","410521198203128847",5,"计算机应用与技术");
System.out.println("----------------教师信息----------------------");
System.out.println(teaPeople);
}
}
----------------学生信息--------------------- 姓名:王丽丽 年龄:23 性别:女 身份证号:410521198902145589 学号:00001 所学专业:计算机应用与技术 ----------------教师信息---------------------- 姓名:张文 年龄:30 性别:男 身份证号:410521198203128847 教龄:5 所教专业:计算机应用与技术
Single inheritance
class Student extends Person,Person1,Person2{…}
class Student extends Person,extends Person1,extends Person2{…}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
