这个Java题怎么做?要解析.

来源:百度知道 编辑:UC知道 时间:2024/06/24 01:35:18
public class Test extends TT{
public static void main(String args[]){
Test t=new Test("Tom.");
}
public Test(String s){
super(s);
System.out.print("How are you?");
}
public Test(){
this("I am Jack.");
}
}
class TT{
public TT(){
System.out.print("Hi!");
}
public TT(String s){
this();
System.out.print("I am "+s);
}
}
求输出的结果。

直接先看主方法(main()),Test t=new Test("Tom.");

这句话表示在堆空间里面new出一个新对象--带参数的Test(t),

由于Test是是继承的TT的方法 直接看class TT

先输出Hi! 由于TT的方法被重载了 public TT(String s)

所以程序继续执行"I am"+s 在String里面找s 先引用自身

由于不带参数,所以执行public Test() 输出 I am Jack

super(s) 先引用父类的s 然后输出 How are you?

结果 Hi!I am Tom.How are you?

public class Test extends TT{
public static void main(String args[]){
// 1.程序入口
Test t=new Test("Tom."); //调参数为String的构造方法到2
}
public Test(String s){ // 2.到这里
super(s); //调父类的参数为String的构造方法到3
System.out.print("How are you?"); //6.到这里输出
}
public Test(){
this("I am Jack.");
}
}
class TT{
public TT(){ //4.到这里
System.out.print("Hi!"); //输出后返回到5
}
public TT(String s){ //3.到这里
this(); // 调本类的无参构造方法 到4
System.out.print("I am "+s); // 5.到这里输出后返回到6
}