一道面试题,写出下列程序的运行结果:class Children{
int num;
Children(int er)
{
System.out.println(“Children(“ + er + “)”);
}
}
class Parent
{
static Children child1 = new Children(1);
Parent();
{
System.out.println(“Parent()”);
Child3 = new Children(33);
}
Children child2 = new Children(2);
Void relation()
{
System.out.println(“relation()”);
}
static Children child3 = new Children(3);
}
public class ObjectInit1
{
Parent.child3.num = 1;
System.out.println(“main begins”);
Parent mother = new Parent();
Mother.relation();
}
int num;
Children(int er)
{
System.out.println(“Children(“ + er + “)”);
}
}
class Parent
{
static Children child1 = new Children(1);
Parent();
{
System.out.println(“Parent()”);
Child3 = new Children(33);
}
Children child2 = new Children(2);
Void relation()
{
System.out.println(“relation()”);
}
static Children child3 = new Children(3);
}
public class ObjectInit1
{
Parent.child3.num = 1;
System.out.println(“main begins”);
Parent mother = new Parent();
Mother.relation();
}
姑且把它看做main方法
public class ObjectInit1
{
public static void main(String[] args) {
Parent.child3.num = 1;
System.out.println(“main begins”);
Parent mother = new Parent();
Mother.relation();
}
}这样的话应该输出
Children(1)
Children(3)
main begins
Children(2)
Parent()
Children(33)
relation大概是这样吧,代码先执行后执行的问题,首先你要记住classload的时候先执行static代码,生成实例时先执行声明的部分,然后再是构造函数
Children(2)
Parent()
Children(33)
relation()
Children(1)
Children(3)
main begins
Children(2)
Parent()
Children(33)
relation()
看到这个题时偶也在奇怪,怎么没有main方法,这是别人给我的资料里的。
但是还是感谢大家在百忙中给予解答。谢谢