类和对象2
请写出以下程序运行结果
class Window {
Window(int marker) { System.out.println("Window(" + marker + ")"); }
}
class House {
Window w1 = new Window(1);
House() {
System.out.println("House()");
w3 = new Window(33);
}
Window w2 = new Window(2);
void f() {
System.out.println("f()");
}
static Window w3 = new Window(3);
}
public class Est {
public static void main(String[] args) {
House h = new House();
h.f();
}
}
答案:
Window(3)
Window(1)
Window(2)
House()
Window(33)
f()
此题涉及构造器初始化的问题:类中各属性的初始化顺序 ,构造器和初始化块
请写出以下程序运行结果:
public class Test {
private int i = 0;
Test increment() {
i++;//私有成员变量
return this.clone();
}
public Test clone() {
Test t = new Test();初始化一次,输出一个0
t.i = i;
return t;
}
public Test() { System.out.print(i); }
void print() {
System.out.printf("i = %d", i);
}
public static void main(String[] args) {
Test x = new Test();//初始化一次,输出一个0
for ( int i=0; i<10; i++ )//这里的i是局部变量
x = x.increment();
x.print();
}
}
答案:
00000000000i = 10
子类与继承2
Object是Java中所有类的共同父类。 T