(原創) derived-class要怎麼呼叫base-class的constructor? (Java)
有時我們在derived-class的constructor提供的參數,事實上是base-class的資料,或者base-class根本就是ABC(abstract base class),這時我們就得在derived-class的constructor去呼叫base-class的constructor。
Constructor_CallBaseConstructor_student.java
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename : Constructor_CallBaseConstructor_student.java
5Compiler : eclipse 3.2.1 / Java SE 6
6Description : No defualt constructor is OK in Java
7Release : 02/16/2007 1.0
8*/
9package javalab;
10
11public class Constructor_CallBaseConstructor_student {
12 public String name;
13
14 public Constructor_CallBaseConstructor_student(String name) {
15 this.name = name;
16 }
17}
Constructor_CallBaseConstructor_bachelor.java
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename : Constructor_CallBaseConstructor_bachelor.java
5Compiler : eclipse 3.2.1 / Java SE 6
6Description : No defualt constructor is OK in Java
7Release : 02/16/2007 1.0
8*/
9package javalab;
10
11public class Constructor_CallBaseConstructor_bachelor extends Constructor_CallBaseConstructor_student {
12 public String lab;
13
14 public Constructor_CallBaseConstructor_bachelor(String name, String lab) {
15 super(name);
16 this.lab = lab;
17 }
18
19 public static void main(String[] args) {
20 Constructor_CallBaseConstructor_bachelor bachelor = new Constructor_CallBaseConstructor_bachelor("John","PECLab");
21 System.out.println(bachelor.name);
22 System.out.println(bachelor.lab);
23 }
24}
執行結果
PECLab
Constructor_CallBaseConstructor_bachelor.java的14行的constructor提供了兩個參數,name為base-class的資料,而lab為derived-class的資料,所以勢必呼叫base-class的constructor才行,Java的方式是在body使用super keyword,並帶入參數,這樣就可以執行base-class的constructor了。
C++是在constructor initializer list使用呼叫base-class的constructor,而C#是在constructor initializer list中使用base這個keyword。
See Also
(原創) derived-class要怎麼呼叫base-class的constructor? (初級) (C++) (OO C++)
(原創) derived-class要怎麼呼叫base-class的constructor? (初級) (C#)