继承

Java继承的限制

1.Java不允许多重继承

一个子类不能继承多个父类。 比如 C 想要继承 A B两个类,则是不允许的。

class A{}

class B{}

class C extends A B{}  -----错误

可以多层继承。可以A继承B,C再继承A。

class A{}

class B  extends A{}

class C  extends B{}--------正确

2.子类继承父类的时候严格来讲会继承父类的全部操作,但是对于所有的私有操作隐式继承,对于共有操作,显式继承。

3.在子类对象构造之前默认调用父类的无参构造函数。

父类中有无参构造时候子类加super() 加与不加没有区别。

如果父类总没有无参构造函数,那么就用super()明确调用有残构造方法。

如果 super() 和this()都要放在首行。。。。super()与this()不能同时出现,

----父类先初始化,子类才初始化。。

class Person{
    private String name ;
    private int age ;
    public Person(String name, int age ){
        this.name = name ;
        this.age = age ;
    }
    public void setName(String name){
        this.name = name ;
    }
    public void setAge(int age){
        this.age = age ;
    }
    public String getInfo(){
        return "Name : " + this.name + ", Age " + this.age ;
    }
    public String getName(){
        return this.name;
    }
    public int getAge(){
        return this.age;
    }
}
class Student extends Person{
    private String school ;
    public Student(String name , int age , String school){
        super(name,age) ;  //传入参数。
        this.school = school ;
    }
    public void setSchool(String school){
        this.school = school ;
    }
    public String getShool(){
        return this.school ;
    }
    
}
public class Jicheng{
    public static void main(String atgs[]){
        Student stu = new Student ("zhuopeng",20,"pingyao") ;
        System.out.println(stu.getInfo() );
    }
}








原文地址:https://www.cnblogs.com/da-peng/p/5122279.html