Java构造函数

Java构造函数使用方法:

  1. 构造函数与类同名(大小写完全一致),无返回值;
  2. 构造函数可重载(overloaded);
  3. 构造函数随“new”调用。

继承(inheritance)中的构造函数:

  1. 子类的构造过程必须调用父类的构造构造方法
  2. 子类使用super(XXX)调用父类构造方法;
    1. 如果调用super(XXX)方法,程序默认调用父类无参数的构造方法,等同于super();
    2. 若调用super(XXX)方法,则必须出现在子类构造方法的第一行。

例子:

 1 class A {
 2     protected void print(String s) {
 3         System.out.println(s);
 4     }
 5     A() {
 6         print("A()");
 7     }
 8     public void f() {
 9         print("A:f()");
10     }
11 }
12 
13 class B extends A{
14     B(){
15         print("B()");
16     }
    //重写了class A中的f()
17 public void f() { 18 print("B:f()"); 19 } 20 public static void main(String arg[]) { 21 B b = new B(); 22 b.f(); 23 } 24 }

分析输出结果,体会上面几点。

例子输出结果:

1 A()
2 B()
3 B:f()
View Code

 

posted @ 2017-04-16 16:16  Cynthia_chao  阅读(226)  评论(0编辑  收藏  举报