java是否允許返回值類型不同的重載overload或者覆蓋override

重載是一定不允許的。比如
Java代碼 複製代碼 收藏代碼
  1. class Super{   
  2.     void f(){   
  3.            
  4.     }   
  5.     int f(){   
  6.         return 1;   
  7.     }   
  8. }  
class Super{
	void f(){
		
	}
	int f(){
		return 1;
	}
}


原因在與如果調用時int i = f();可以知道是調用Sub的f()。但是,往往用戶不關心返回值。只是f()。這樣就無法確定到底是哪個。

覆蓋一般情況是不允許的。比如


Java代碼 複製代碼 收藏代碼
  1. class Super{   
  2.     void f(){   
  3.            
  4.     }   
  5. }   
  6. class Sub extends Super{   
  7.     int f(){   
  8.         return 1;   
  9.     }   
  10. }  
class Super{
	void f(){
		
	}
}
class Sub extends Super{
	int f(){
		return 1;
	}
}


編譯會報錯。
但是有辦法可以不同(表面上不同)。比如

Java代碼 複製代碼 收藏代碼
  1. class Grain{   
  2.     public String toString(){   
  3.         return "Grain";   
  4.     }   
  5. }   
  6. class Wheat extends Grain{   
  7.     public String toString(){   
  8.         return "Wheat";   
  9.     }   
  10. }   
  11. class Mill{   
  12.     Grain process(){//注意返回值   
  13.         return new Grain();   
  14.     }   
  15. }   
  16. class WheatMill extends Mill{   
  17.     Wheat process(){//注意返回值   
  18.         return new Wheat();   
  19.     }   
  20. }   
  21. public class CovariantReturn {   
  22.     public static void main(String[] args) {   
  23.         Mill m = new Mill();   
  24.         Grain g = m.process();   
  25.         System.out.println(g);   
  26.            
  27.         m = new WheatMill();   
  28.         g = m.process();   
  29.            
  30.         System.out.println(g);   
  31.     }   
  32. }  
class Grain{
	public String toString(){
		return "Grain";
	}
}
class Wheat extends Grain{
	public String toString(){
		return "Wheat";
	}
}
class Mill{
	Grain process(){//注意返回值
		return new Grain();
	}
}
class WheatMill extends Mill{
	Wheat process(){//注意返回值
		return new Wheat();
	}
}
public class CovariantReturn {
	public static void main(String[] args) {
		Mill m = new Mill();
		Grain g = m.process();
		System.out.println(g);
		
		m = new WheatMill();
		g = m.process();
		
		System.out.println(g);
	}
}


這樣是完全可以的,運行結果

Grain
Wheat

其實也並不難理解,因爲子類本身就可以看做是父類。這個是JAVA1.5後引入的一個概念:
協變返回類型


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章