当前位置: 技术问答>java相关
帮我看看这道scjp题
来源: 互联网 发布时间:2015-04-13
本文导语: public class Star { Star() { System.out.println("Star"); } Star(String s1) { super(); System.out.println(s1 + " is a Star"); } Star(String s2, String s3) { this("Mercury"); System.out.println( s2 + " and ...
public class Star {
Star() {
System.out.println("Star");
}
Star(String s1) {
super();
System.out.println(s1 + " is a Star");
}
Star(String s2, String s3) {
this("Mercury");
System.out.println( s2 + " and " + s3 + " are also Stars");
}
public static void main(String [] args) {
Sun sun = new Sun();
Sun sun1 = new Sun("Venus");
Sun sun2 = new Sun("Mars", "Earth");
}
}
class Sun extends Star {
public Sun() {
System.out.println("Star Wars1");
}
public Sun(String v1) {
super(v1, "Saturn");
System.out.println("Star Wars2");
}
public Sun(String v2, String v3) {
if ( v2.substring(0, v2.length()).length() > v3.length())
System.out.println("Mission to Mars");
else
System.out.println("Earth");
}
}
output:
1.Star
2.Star Wars1
3.Mercury is a Star.
4.Venus and Saturn are also Stars.
5.Star Wars2
6.Star
7.Earth
1-4还好理解,但5-7是为什么呢?望高手指点迷津,谢谢
Star() {
System.out.println("Star");
}
Star(String s1) {
super();
System.out.println(s1 + " is a Star");
}
Star(String s2, String s3) {
this("Mercury");
System.out.println( s2 + " and " + s3 + " are also Stars");
}
public static void main(String [] args) {
Sun sun = new Sun();
Sun sun1 = new Sun("Venus");
Sun sun2 = new Sun("Mars", "Earth");
}
}
class Sun extends Star {
public Sun() {
System.out.println("Star Wars1");
}
public Sun(String v1) {
super(v1, "Saturn");
System.out.println("Star Wars2");
}
public Sun(String v2, String v3) {
if ( v2.substring(0, v2.length()).length() > v3.length())
System.out.println("Mission to Mars");
else
System.out.println("Earth");
}
}
output:
1.Star
2.Star Wars1
3.Mercury is a Star.
4.Venus and Saturn are also Stars.
5.Star Wars2
6.Star
7.Earth
1-4还好理解,但5-7是为什么呢?望高手指点迷津,谢谢
|
哥们,第五项 "Star Wars2" 是随着第四项也就是 初始化 sun1 的最后一条语句。执行完“super(v1, "Saturn"); "不正好执行System.out.println("Star Wars2"); 吗!
第6项,7项是初始化sun2执行的。因为sun2中没有super(""), 所以引式的调用父类star的构造函数
Star() {
System.out.println("Star");
}
因为字符串Mars的个数少于earth的个数,所以执行
else
System.out.println("Earth");
即第七项
第6项,7项是初始化sun2执行的。因为sun2中没有super(""), 所以引式的调用父类star的构造函数
Star() {
System.out.println("Star");
}
因为字符串Mars的个数少于earth的个数,所以执行
else
System.out.println("Earth");
即第七项
|
当子类的构造器没有显式调用超类的任何构造器,则会隐式调用超类的默认构造器。