SCJP題庫第051題


1. public interface A{
2.   public void doSomething(String thing);
3. }
1. public class AImpl implements A{
2.   public void doSomething(String msg){}
3. }
1. public class B{
2.   public A doit(){
3.     //more code here
4.   }
5.
6.   public String execute(){
7.     //more code here
8.   }
9. }
 
1. public class C extends B{
2.   public AImpl doit(){
3.     //more code here
4.   }
5.
6.   public Object execute(){
7.     //more code here
8.   }
9. }
Which statement is true about the classes and interfaces?
A. Compilation will succeed for all classes and interfaces.
B. Compilation of class C will fail because of an error in line 2.
C. Compilation of class C will fail because of an error in line 6.
D. Compilation of class AImpl will fail because of an error in line 2.
Ans:C
解說:
Overriding 規則:方法名、參數、回傳皆要和父類別中的方法一樣,此例類別C中的execute方法其傳回值是Object,與父類別B中的execute中的傳回值String不同,類別C中的execute允許傳回非String類別物件,因為以最大的Object限定傳回值型態,而Object是所有類別的父類別,也就是說類別Cexecute有可能傳回非String類別型態,違背覆載的規則。


String is an Object. 但Object未必一定是String…

Comments

Popular posts from this blog

Android+Google Map API v3 Geocoding(地址轉經緯度度