正在加载图片...
Thinking in Java 3 Edition interface I3 int f()i) class ct public int f() return li 1 class C2 implements Il, I2 public void f()I public int f(int i)i return l;// overloaded class C3 extends c implements I2 public int f(int i) return l; ) / overloaded } class C4 extends c implements I3 / Identical, no probl public int f() return 1 / Methods differ only by return type //! class C5 extends c implements I1 t // interface I4 extends Il, I3///: N 这个难题要归因于覆写、实现和重载的不期而遇,以及“不能仅通过返回 值来辨别重载的方法”。如果把最后两行的注释去掉,就会出现如下的错 误信息 Interface Collision java: 23: f() in C cannot implement f() in Ii; attempting to use incompatible return type found: int required: void Interface Collision java: 24: interfaces 13 and I1 are incompatible; both define f( but with different return type 而且在要合并的接口里面放上同名方法,通常也会破坏程序的可读性。所 以别这么做 用继承扩展 interface 你可以用继承,往 interface里面添加新的方法,也可以用继承把多个 interface合并成一个新的 interface。在这两种情况下,你所得到的 都只是一个新的 interface,就像下面这样: //: c08: Horrorshow. java / Extending an interface with inheritance nterface Monster i interface DangerousMonster extends Monster i void destroy()i 第8页共47页 www.wgqqh.com/shhgs/tij.html email:shhgs@sohu.comThinking in Java 3 rd Edition www.wgqqh.com/shhgs/tij.html email:shhgs@sohu.com ✄ 8 ☎ ✆ 47 ☎ interface I3 { int f(); } class C { public int f() { return 1; } } class C2 implements I1, I2 { public void f() {} public int f(int i) { return 1; } // overloaded } class C3 extends C implements I2 { public int f(int i) { return 1; } // overloaded } class C4 extends C implements I3 { // Identical, no problem: public int f() { return 1; } } // Methods differ only by return type: //! class C5 extends C implements I1 {} //! interface I4 extends I1, I3 {} ///:~ ×U¹%Óæ)â«ã ñíä(X@à± EÃÍX;<^ef gQå¨ä(µÏÄÅPbe}(æ¸ º!íĎ(Æ çèéL InterfaceCollision. java: 23: f( ) in C cannot implement f( ) in I1 ; attempting to use incompatible return type found : int required: void InterfaceCollision. java: 24: interfaces I3 and I1 are incompatible; both define f( ), but with different return type à³F%°ž(˶kJ‡Ñµ ·[ºêâ%(Ý*D E¨ ZT  i n terface ¡ÝEˆö8 ë in terface ˶ìäÂ(µ [ÝEˆö8PV× in terface °žŽ3×Â( in terfaceF e†´Ž ¡D‰g( Æó3×Â( interface }Ž¶ ¦L //: c08:HorrorShow.java // Extending an interface with inheritance. interface Monster { void menace(); } interface DangerousMonster extends Monster { void destroy(); }
<<向上翻页向下翻页>>
©2008-现在 cucdc.com 高等教育资讯网 版权所有