继承
继承:子类可以继承父类共有的属性和方法。
关键字: extends
继承的优点:实现类的重用,减少代码的冗余。
特征:子类继承了父类后:
子类可以访问父类中的公有的属性,对象可以直接访问父类的属性
子类可以访问父类中的方法, 对象可以直接访问父类的方法。
子类可以重写父类中的方法。
举例
父类:
public class People {
private String name;
private int age;
private String id;
private String sex;
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 getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public People() {
}
public People(String name, int age, String id, String sex) {
this.name = name;
this.age = age;
this.id = id;
this.sex = sex;
}
}
子类:
public class Student extends People {
private String stuNo;
// 子类构造方法 无参
public Student(){
super();
System.out.println("学生类的无参构造方法被调用");
}
public Student(String name){
//this(); 调用当前的构造方法
//super(); 调用父类的构造方法
}
//有参构造方法
public Student(String name, int age, String id, String sex,String stuNo){
super(name, age, id, sex); //调用父类中的构造方法
this.stuNo = stuNo;
}
//this super 各自的用法
public void show(){
System.out.println(this.stuNo);
System.out.println(super.getName());
}
}
测试类:
public class Test {
public static void main(String[] args){
People people = new People();
Student student = new Student("张三",18,"1001","女","1001");
System.out.println(student. getName());