继承
作用:解决代码被重复使用的问题。
一般将公共的代码抽取出来,放到一个类时,这个类被称为父类;
满足的条件
1.父类取名 is、、a的关系 Student is Person
2.继承关键字 extends
创建Person类:属性 name,age,tel。方法 study
package 练习三;
//创建Person类:属性 name,age,tel。方法 study
public class Person {
private String name ;
private int age ;
private String tel ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public void study(){
System.out.println("我在学习呢");
}
}
子类Student, 独有属性:学号,学费
package 练习三;
public class Student extends Person{
private int xh ;
private int xf ;
public int getXh() {
return xh;
}
public void setXh(int xh) {
this.xh = xh;
}
public int getXf() {
return xf;
}
public void setXf(int xf) {
this.xf = xf;
}
// 使用继承完成,在main方法内,分别创建Student和Teacher对象,调用set方法赋值,输出属性值
public static void main(String[] args) {
Student student = new Student();
student.setName("张三");
student.setAge(18);
student.setTel("18570472323");
student.setXf(19200);
student.setXh(41);
String name = student.getName();
int age = student.getAge();
String tel = student.getTel();
int xf = student.getXf();
int xh = student.getXh();
System.out.println("姓名为"+name+",年龄为: "+age+",电话为: "+tel+",学费为: "+xf+",学号为: "+xh);
student.study();
}
}
子类Teacher 独有属性: 工资
package 练习三;
public class Teacher extends Person{
private int gz ;
public int getGz() {
return gz;
}
public void setGz(int gz) {
this.gz = gz;
}
public static void main(String[] args) {
Teacher teacher = new Teacher();
teacher.setName("张三");
teacher.setAge(18);
teacher.setTel("185704723");
teacher.setGz(30000);
String name = teacher.getName();
int age = teacher.getAge();
String tel = teacher.getTel();
int gz = teacher.getGz();
System.out.println("姓名为"+name+",年龄为: "+age+",电话为: "+tel+",月工资为: "+gz);
}
}