java构造器

 

转自:https://www.runoob.com/java/java-inheritance.html

子类是不继承父类的构造器(构造方法或者构造函数)的,它只是调用(隐式或显式)。

如果父类的构造器带有参数,则必须在子类的构造器中显式地通过 super 关键字调用父类的构造器并配以适当的参数列表

如果父类构造器没有参数,则在子类的构造器中不需要使用 super 关键字调用父类构造器,系统会自动调用父类的无参构造器。

 1 package 构造器;
 2 class SuperClass{
 3     private int n;
 4     SuperClass(){
 5         System.out.println("SuperClass()");
 6     }
 7     SuperClass(int n){
 8         this.n = n;
 9         System.out.println("SuperClass(int n):"+n);
10         
11     }
12 }
13 class SubClass extends SuperClass{
14     private int n;
15     SubClass(){
16         System.out.println("SubClass()");
17     }
18     SubClass(int n){
19         super(300);
20         System.out.println("SubClass(int n):"+n);
21         this.n = n;
22     }
23 }
24 class SubClass2 extends SuperClass{
25     private int n;
26     SubClass2(){
27         super(400);
28         System.out.println("SubClass2()");
29     }
30     SubClass2(int n){
31         System.out.println("SubClass2(int n):"+n);
32         this.n = n;
33     }
34 }
35 public class TestSuperSubclass {
36     public static void main(String[] args) {
37         System.out.println("------SubClass继承------");
38         new SubClass();
39         System.out.println("-----------------------");
40         new SubClass(100);
41         System.out.println("------SubClass2继承------");
42         new SubClass2();
43         System.out.println("-----------------------");
44         new SubClass2(100);
45     }
46 }

运行结果:

------SubClass继承------
SuperClass()
SubClass()
-----------------------
SuperClass(int n):300
SubClass(int n):100
------SubClass2继承------
SuperClass(int n):400
SubClass2()
-----------------------
SuperClass()
SubClass2(int n):100

 

posted @ 2019-07-17 16:46  逍遥天地间  阅读(206)  评论(0编辑  收藏  举报