一个问题

uioppp 2006-02-22 03:48:08
package test;
public class FatherClass
{
public FatherClass()
{
System.out.println("FatherClass Create");
}
}
子类:
package test;
import test.FatherClass;
public class ChildClass extends FatherClass
{
public ChildClass()
{
System.out.println("ChildClass Create");
}

public static void main(String[] args)
{
FatherClass fc = new FatherClass();
ChildClass cc = new ChildClass();
}
}
执行子类的结果为什么是:
FatherClass Create
FatherClass Create
ChildClass Create


FatherClass Create 为什么会打印二次??
...全文
93 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
aywrenyue 2006-02-22
  • 打赏
  • 举报
回复
ChildClass cc = new ChildClass(); 在创建子类对象时,首先要调用super class地构造函数,逐级向上调用。
所以在 new ChildClass()的时候,执行顺序是FatherClass() ——〉ChildClass()
interpb 2006-02-22
  • 打赏
  • 举报
回复
public A getA(String s) {
class AImpl implements A{
private String b;
private AImpl() {
b = s;
}
public String getB() {
return b;
}
public void test() {

}
}
return new AImpl();
}
//ok
fay921 2006-02-22
  • 打赏
  • 举报
回复
接口没有被实现
uioppp 2006-02-22
  • 打赏
  • 举报
回复
up
uioppp 2006-02-22
  • 打赏
  • 举报
回复
再问一个问题:

在网上看到一面试题,请教各位答案。

下面代码是否正确?要如何修改??
public interface A{
void test();
}

public A getA(String s) {
class AImpl implements A{
private String b;
private AImpl() {
b = s;
}
public String getB() {
return b;
}
}
return new AImpl();
}
interpb 2006-02-22
  • 打赏
  • 举报
回复
public ChildClass()
{
System.out.println("ChildClass Create");
}


这里实际上相当于
public ChildClass()
{
super();//调用父类的构造函数
System.out.println("ChildClass Create");
}

因为子类对象包含一个父类的子对象,必须要先调用父类的构造函数初始化父类子对象

所以你的程序中调用了两次 fatherclass()
infowain 2006-02-22
  • 打赏
  • 举报
回复
子类继承了父类的构造方法
奥爸 2006-02-22
  • 打赏
  • 举报
回复
创建 ChildClass的时候,会调用 基类的构造

62,629

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧