课程5.3之子类实例化

转发请注明出处:
安卓猴的博客(http://sunjiajia.com)

本节课程将学习以下内容:

  • 生成子类的过程
  • 使用super调用父类构造函数的方法

生成子类的过程

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

注意:

  • 在子类的构造函数中,必须调用父类的构造函数;
  • super所调用的是父类的哪个构造函数,是由super(参数)中的参数个数决定;
  • super(参数);必须是构造函数的第一行。

例子:(请动手)

1.新建一个名为Person.java的Java源文件:

class Person{
  String name;
  int age;
  Person(){
    System.out.println("Person的无参数构造函数");
  }
  Person(String name, int age){
    this.name = name;
    this.age = age;
    System.out.println("Person的有参数构造函数");
  }
  void eat(){
    System.out.println("吃东西");
  }
  void introduce(){
    System.out.println("我的名字叫 " + this.name + ",我的年龄 " + this.age);
  }
}

2.新建一个名为Student.java的Java源文件:

class Student extends Person{
  int grade;
  Student(){
    System.out.println("Student的无参数构造函数");
  }

  Student(String name, int age, int grade){
    // 调用父类Person当中的有两个参数name和age的构造函数
    super(name, age);
    this.grade = grade;
    System.out.println("Student的有参数构造函数");
  }

  void study(){
    System.out.println("我学习的年级是 " + this.grade);
  }
}

3.新建一个名为Demo01.java的Java源文件:

class Demo01{
  public static void main(String[] args) {
    Student stu01 = new Student("zhang3",18,3);
    stu01.eat();
    stu01.introduce();
    stu01.study();
  }
}
    原文作者:GitOPEN
    原文地址: https://www.jianshu.com/p/d69a01ff4304
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞