谁能写出如下代码的输出?并说明为什么。
public class Test {
public static void main(String[] args) {
Animal x = new Tiger();
System.out.println("(1)x.news is " + x.news);
System.out.println("(2)((Tiger)x).news is " + ((Tiger)x).news);
System.out.println("(3)x.smile() is " + x.smile());
System.out.println("(4)((Tiger)x).smile() is " + ((Tiger)x).smile());
System.out.println("(5)x.getNews() is " + x.getNews());
System.out.println("(5)x.getMessage() is " + x.getMessage());
}
}
class Animal {
public String news = "Animal's news";
public String message = "Animal's message";
public static String smile() {
return "smile from Animal";
}
public String getNews() {
return news;
}
public String getMessage() {
return message;
}
}
class Tiger extends Animal {
public String news = "Tiger's news";
public String message = "Tiger's message";
public static String smile() {
return "smile from Tiger";
}
public String getNews() {
return news;
}
}
这是输出结果:
(1)x.news is Animal's news
(2)((Tiger)x).news is Tiger's news
(3)x.smile() is smile from Animal
(4)((Tiger)x).smile() is smile from Tiger
(5)x.getNews() is Tiger's news
(5)x.getMessage() is Animal's message
下边有注释:
public class a {
public static void main(String[] args) {
Animal x = new Tiger(); //实例化一个Tiger
System.out.println("(1)x.news is " +this. x.news); //调用Animal的news
System.out.println("(2)((Tiger)x).news is " + ((Tiger)x).news); //调用Tiger的news
System.out.println("(3)x.smile() is " + this.x.smile()); //调用Animal的smile()
System.out.println("(4)((Tiger)x).smile() is " + ((Tiger)x).smile()); //调用Tiger的smile()
System.out.println("(5)x.getNews() is " + x.getNews()); //调用Tiger的getNews(),因为Tiger继承了Animal中的所有方法,并且覆写所以调用的是Tiger的getNews()
System.out.println("(5)x.getMessage() is " + x.getMessage());//调用Animal的getMessage() 因为Tiger继承了Animal中的所有方法,但是没有覆写getMessage()所以调用Animal getMessage()
}
}
class Animal {
public String news = "Animal's news"; //声明news变量
public String message = "Animal's message"; //声明message变量
public static String smile() {
return "smile from Animal";
}
public String getNews() { //getNews()方法
return news;
}
public String getMessage() { //getMessage()方法
return message;
}
}
class Tiger extends Animal {
public String news = "Tiger's news"; //声明news变量
public String message = "Tiger's message"; //声明message变量
public static String smile() {
return "smile from Tiger"; //smile() 方法
}
public String getNews() {
return news; //覆写getNews()方法
}
}