万达总部林宁联系方式:java程序问题
来源:百度文库 编辑:杭州交通信息网 时间:2024/05/08 00:59:17
为什么会不同输出
第一个程序 问号地方不一样
public class TestA {
TestA() {??????????
System.out.println("P ");
this.init();
}
void init() {?????????
System.out.println("Q ");
}
public static void main(String[] args) {
TestB testb = new TestB();
}
}
class TestB extends TestA {
int i = 1;
TestB() {
super();
System.out.println(i + " ");
}
void init() {???????
System.out.println("C ");
this.i = 2;
System.out.println(i + " ");
}
} 输出是 p c 2 1
2个程序
public class TestA {
TestA() {
System.out.println("P ");
this.initw();???????
}
void initw() {?????
System.out.println("Q ");
}
public static void main(String[] args) {
TestB testb = new TestB();
}
}
class TestB extends TestA {
int i = 1;
TestB() {
super();
System.out.println(i + " ");
}
void inita() {?????????
System.out.println("C ");
this.i = 2;
System.out.println(i + " ");
}
}输出是 p q 1
第3个
public class TestA {
TestA() {
System.out.println("P ");
this.init();????????
}
void init() {??????????
System.out.println("Q ");
}
public static void main(String[] args) {
TestB testb = new TestB();
}
}
class TestB extends TestA {
int i = 1;
TestB() {
super();
System.out.println(i + " ");
}
void inita() {????????
System.out.println("C ");
this.i = 2;
System.out.println(i + " ");
}
} 输出是 p q 1
为什么会不同输出
第一个程序 问号地方不一样
public class TestA {
TestA() {??????????
System.out.println("P ");
this.init();
}
void init() {?????????
System.out.println("Q ");
}
public static void main(String[] args) {
TestB testb = new TestB();
}
}
class TestB extends TestA {
int i = 1;
TestB() {
super();
System.out.println(i + " ");
}
void init() {???????
System.out.println("C ");
this.i = 2;
System.out.println(i + " ");
}
} 输出是 p c 2 1
2个程序
public class TestA {
TestA() {
System.out.println("P ");
this.initw();???????
}
void initw() {?????
System.out.println("Q ");
}
public static void main(String[] args) {
TestB testb = new TestB();
}
}
class TestB extends TestA {
int i = 1;
TestB() {
super();
System.out.println(i + " ");
}
void inita() {?????????
System.out.println("C ");
this.i = 2;
System.out.println(i + " ");
}
}输出是 p q 1
第3个
public class TestA {
TestA() {
System.out.println("P ");
this.init();????????
}
void init() {??????????
System.out.println("Q ");
}
public static void main(String[] args) {
TestB testb = new TestB();
}
}
class TestB extends TestA {
int i = 1;
TestB() {
super();
System.out.println(i + " ");
}
void inita() {????????
System.out.println("C ");
this.i = 2;
System.out.println(i + " ");
}
} 输出是 p q 1
为什么会不同输出
这个问题很简单
第一个程序,子类中的init函数覆盖掉了父类中的init函数,所以在父类的构造函数中调用的init实际上是子类中的
第二、三个程序中,子类中的子类中的inita其实并没有被调用,父类中调用的是子类继承自父类的init函数