关于Java中的构造函数:
同C++一样,Java的构造函数也是先基类构造函数再派生类构造函数的调用顺序。
同C++不同,=的赋值并不会引起copy构造函数的调用,而是必须通过class InstanceA = new class(InstanceB)的形式。
Java并没有初始化列表一类的东西,但是有初始化块,其定义为一个代码块,如果为非static,则在构造对象时执行一次。如果为static,则在类加载时执行一次。
通过this重载构造函数,则其必须为第一条语句。
以下是一个例子:
package LearnJava;
/**
* Created by Jimmy on 2015/5/28.
*/
class Foo{
public Foo(){
System.out.println("Foo constructor without arg.");
}
public Foo(Foo f){
System.out.println("Foo copy constructor.");
}
}
class Bar{
public Bar(){
System.out.println("Bar constructor without arg.");
}
public Bar(Bar b){
System.out.println("Bar copy constructor.");
}
}
class Base{
public Base(){
System.out.println("Base constructor without arg.");
}
{
System.out.println("Just a block in class B");
}
}
class Derived extends Base{
public Derived(){
System.out.println("Derived constructor without arg.");
}
public Derived(Foo ff, Bar bb){
System.out.println("Derived constructor(Foo ff, Bar bb) without arg.");
m_foo = new Foo(ff);
m_bar = new Bar(bb);
}
public Derived(Bar bb, Foo ff){
//通过this重载构造函数,则其必须为第一条语句
this(ff, bb);
System.out.println("Derived constructor(Bar bb, Foo ff) without arg.");
}
{
System.out.println("Just a block in class Derived");
}
private Foo m_foo;
private Bar m_bar;
}
public class InitilizeAndCallSequence {
public static void main(String[] args){
Foo foo = new Foo();
Bar bar = new Bar();
System.out.println("##### test start #####");
System.out.println("test case 1:");
Derived derived_1 = new Derived();
System.out.println("test case 2:");
Derived derived_2 = new Derived(foo, bar);
System.out.println("test case 3:");
Derived derived_3 = new Derived(bar, foo);
System.out.println("##### test end #####");
}
}
执行结果是:
Foo constructor without arg.
Bar constructor without arg.
##### test start #####
test case 1:
Just a block in class B
Base constructor without arg.
Just a block in class Derived
Derived constructor without arg.
test case 2:
Just a block in class B
Base constructor without arg.
Just a block in class Derived
Derived constructor(Foo ff, Bar bb) without arg.
Foo copy constructor.
Bar copy constructor.
test case 3:
Just a block in class B
Base constructor without arg.
Just a block in class Derived
Derived constructor(Foo ff, Bar bb) without arg.
Foo copy constructor.
Bar copy constructor.
Derived constructor(Bar bb, Foo ff) without arg.
##### test end #####
打印信息:
1, test case1, 默认构造函数
2,test case2, 带参数构造函数
3, test case3, 重载带参数构造函数