继承的概念
继承就是子类继承父类的特征和行为,使得子类对象(实例)具有父类的属性和方法,或子类从父类继承方法,使得子类具有父类相同的行为。
继承的优势
减少代码量,降低维护成本。
以Java为例
class Inheritance_1 {
private int age;
private String name;
public Inheritance_1(int age,String name){
this.age=age;
this.name=name;
}
public void eat(){
System.out.println(name+" is eating......");
}
public void sleep(){
System.out.println(name+" is sleeping......");
}
public void Introduce(){
System.out.println("Hello,everyone.I am "+name+",I am "+age+" years old.");
}
}
class Inheritance_Student extends Inheritance_1 { //继承父类的属性,没有补充自己的私有属性
public Inheritance_Student(int age,String name){
super(age, name);//使用super关键字调用父类方法
}
}
public class Inheritance {
public static void main(String[] args) {
Inheritance_1 in=new Inheritance_1(12,"kwy");
in.eat();
Inheritance_Student ins=new Inheritance_Student(21,"孔文媛");
ins.Introduce();
}
}