solution #1, define a no-parameter constructor for A
class A {
int i;
A() {
}
A(int k) {
i = k;
}
}
class B extends A {
public static void main(String args[]) {
A a = new A(10);
System.out.println(a.i);
}
}
solution #2, define a with-parameter constructor for B, which in turn calls with-parameter constructor for A
class A {
int i;
A(int k) {
i = k;
}
}
class B extends A {
B(int k) {
super(k);
}
public static void main(String args[]) {
A a = new A(10);
System.out.println(a.i);
}
}
solution #3, define a no-parameter constructor for B, which in turn calls with-parameter constructor for A
class A {
int i;
A(int k) {
i = k;
}
}
class B extends A {
B() {
super(56);
}
public static void main(String args[]) {
A a = new A(10);
System.out.println(a.i);
}
}
这里要强调一下。
注意看代码中,并没有创建CtorTest类的对象。
因为直觉上有这么一个误解,构造函数是在函数的构造过程中调用的。也就误以为编译器会在构造某类对象的时候,去做那几条规则的检查,并构造相应的构造函数。
但是实际上不是!构造函数是一个类特性,这是跟类相关的。只要编译某个类的代码,这个构造函数就会生成。
所以,既使没有创建CtorTest类的对象,也会去生成它的构造函数。而不是在执行时按需要生成!
你可以使用这个链接引用该篇文章 http://publishblog.blogchina.com/blog/tb.b?diaryID=3102722
[2005-08-28 00:00:00.0] 构造函数小结
[2005-08-30 00:00:00.0] 构造函数分配内存失败时。。。
[2005-09-22 13:48:24.0] java 异常处理
[2005-09-22 13:43:40.0] Java中的易混问题收集
[2005-09-22 13:46:58.0] Java中的易混问题收集