面向对象 继承
什么是继承:子类可以继承父类共有的属性和方法。继承关键字是:extends
继承的优点:实现类的重用,减少代码的冗余。
package am;
/**
* 人类
*
*
*/
public class People {
public String name;
public String sex;
public int age;
public String id;
public void show(){
System.out.println("人可以思考");
}
}
package am;
/**
*
* 学生类
*
*
*/
public class Student extends People {
public String stuNa;
public void show(){
System.out.println("学生可以思考");
}
}
package am;
public class Test {
public static void main(String[] args) {
People people = new People();
Student stu = new Student();
stu.name = "大黄";
stu.age = 18;
stu.id = "10001";
stu.sex = "男";
System.out.println(stu.name+stu.age+stu.id+stu.sex);
stu.show();
people.show();
}
}
子类继承了父类后:
子类可以访问父类中的公有的属性,对象可以直接访问父类的属性
[子类可以访问父类中的方法]。 对象可以直接访问父类的方法。
子类可以重写父类中的方法
子类不能继承父类的构造方法。也就是说super()不是继承,是调用。
什么叫做重写:
子类重写了父类中的方法:方法名称相同,参数列表相同,返回值相同。
什么叫做重载:
仅仅在一个类中,方法名相同,参数列表不同,与返回值无关。
什么叫做构造方法
在一个类中,方法名称与类名相同,无返回值的方法,叫做构造方法。
package am01;
public class People {
private String name;
private int age;
private String sex;
private String id;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getSex(){
return sex;
}
public void setSex(String sex){
this.sex = sex;
}
public String getId(){
return id;
}
public void setId(String id){
this.id = id;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
//无参构造方法
public People(){
}
public People(String name,String sex,int age,String id){
this.age = age;
this.id = id;
this.name = name;
this.sex = sex;
}
}
package am01;
public class Student extends People {
private String stuNa;
//子类构造方法 无参
public Student(){
System.out.println("Student的无参构造方法");
}
//this() super() 各自的作用
public Student(String name){
//this(); this() 调用当前的构造方法
//super(); super() 调用父类的构造方法
}
//有参构造方法
public Student(String name,String id,String sex,int age,String stuNa){
super(name,sex,age,id);
this.stuNa = stuNa;
}
//this super 各自的用法
public void show(){
System.out.println(this.stuNa);
System.out.println(super.getName());
}
}
this 当前对象
super 父类对象
this() 当前对象的构造方法。
super() 父类对象的构造方法。
子类的构造方法中,会默认调用父类的无参构造方法super()。可以指明调用父类的有参构造方法。
super(); 必须出现在第一行。
package am01;
public class Test {
public static void main(String[] args) {
Student stu = new Student("王泽菲","男","142729",18,"1001");
System.out.println(stu.getName()+stu.getAge());
stu.show();
}
}
在继承关系中,必须现有父,再有子
6316

被折叠的 条评论
为什么被折叠?



