GitOPEN's Home.

《Monkey Java》课程5.3之子类实例化

Word count: 370 / Reading time: 2 min
2015/07/15 Share

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

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

生成子类的过程

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

注意:

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

例子:(请动手)

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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源文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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源文件:

1
2
3
4
5
6
7
8
class Demo01{
public static void main(String[] args) {
Student stu01 = new Student("zhang3",18,3);
stu01.eat();
stu01.introduce();
stu01.study();
}
}

欣慰帮到你 一杯热咖啡
【奋斗的Coder!】企鹅群
【奋斗的Coder】公众号
CATALOG
  1. 1. 生成子类的过程
  2. 2. 使用super调用父类构造函数的方法