Java4Android笔记之Java中的子类实例化过程

来源:互联网 发布:剑网三怎么在淘宝买金 编辑:程序博客网 时间:2024/06/06 23:58

生成子类的过程

首先要明确继承关系中,不能继承构造函数

class Person{    int age;    String name;    Person(){        System.out.println("Person()无参构造函数");    }    Person(String name,int age){        this.age = age;        this.name = name;        System.out.println("Person()有参构造函数");    }    void eat(){        System.out.println("eat");    }    void introduce(){        System.out.println("age = "+age+" , name = "+name);    }}class Student extends Person{    int grade;    //在子类的构造函数当中,必须调用父类的构造函数,为什么呢?因为子类不能继承父类的构造函数,势必会在构造的时候,重复使用某些代码,所以这样设计是为了减少重复代码,例如下面三个参数的构造函数,可以简化成super(name,age);this.grade = grade;    Student(){        //super();不写的话,默认调用父类中的无参数构造函数        System.out.println("Student()无参构造函数");    }    Student(String name,int age,int grade){        this.name = name;        this.age = age;        this.grade = grade;    }    void study(){        System.out.print("study");    }}class Test{    public static void mian(String[] args){        //先输出Person的无参构造函数,再输出Student的无参构造函数        Student stu = new Student();        Student curry = new Student("curry",18,3);        System.out.println(curry.name);        System.out.println(curry.age);        System.out.println(curry.grade);    }}

使用super调用父类构造函数的方法

如上面例子中的`super()、super(name,age)

原创粉丝点击