為什么Super.method();在Java中是不允許的?我讀這個(gè)問題并認(rèn)為,如果一個(gè)人能寫到,那么這個(gè)問題就會(huì)很容易解決(不是說沒有它就解決不了):@Overridepublic String toString() {
return super.super.toString();}我不確定它在很多情況下是否有用,但我想知道為什么如果這樣的東西存在于其他語言中的話,它是不存在的。你們覺得怎么樣?編輯:澄清一下:是的,我知道,這在Java中是不可能的,我并不是真的想念它。這不是我所期望的工作,我很驚訝地看到一個(gè)編譯器錯(cuò)誤。我剛想到這個(gè)主意,想討論一下。
3 回答

慕村9548890
TA貢獻(xiàn)1884條經(jīng)驗(yàn) 獲得超4個(gè)贊
public class Items{ public void add(Item item) { ... }}public class RedItems extends Items{ @Override public void add(Item item) { if (!item.isRed()) { throw new NotRedItemException(); } super.add(item); }}public class BigRedItems extends RedItems{ @Override public void add(Item item) { if (!item.isBig()) { throw new NotBigItemException(); } super.add(item); }}
public class NaughtyItems extends RedItems{ @Override public void add(Item item) { // I don't care if it's red or not. Take that, RedItems! super.super.add(item); }}
RedItems

偶然的你
TA貢獻(xiàn)1841條經(jīng)驗(yàn) 獲得超3個(gè)贊
創(chuàng)建祖先類型的臨時(shí)實(shí)例 將字段的值復(fù)制到 原版
對(duì)象改為臨時(shí)對(duì)象。 對(duì)臨時(shí)對(duì)象調(diào)用目標(biāo)方法 將修改后的值復(fù)制回原始對(duì)象
public class A { public void doThat() { ... }}public class B extends A { public void doThat() { /* don't call super.doThat() */ }}public class C extends B { public void doThat() { Magic.exec(A.class, this, "doThat"); }}public class Magic { public static <Type, ChieldType extends Type> void exec(Class<Type> oneSuperType, ChieldType instance, String methodOfParentToExec) { try { Type type = oneSuperType.newInstance(); shareVars(oneSuperType, instance, type); oneSuperType.getMethod(methodOfParentToExec).invoke(type); shareVars(oneSuperType, type, instance); } catch (Exception e) { throw new RuntimeException(e); } } private static <Type, SourceType extends Type, TargetType extends Type> void shareVars(Class<Type> clazz, SourceType source, TargetType target) throws IllegalArgumentException, IllegalAccessException { Class<?> loop = clazz; do { for (Field f : loop.getDeclaredFields()) { if (!f.isAccessible()) { f.setAccessible(true); } f.set(target, f.get(source)); } loop = loop.getSuperclass(); } while (loop != Object.class); }}
添加回答
舉報(bào)
0/150
提交
取消