2011-11-26 44 views
3

假设我有这三类:我可以从super超级方法调用重写的方法吗?

class Foo { 
    void fn() { 
     System.out.println("fn in Foo"); 
    } 
} 

class Mid extends Foo { 
    void fn() { 
     System.out.println("fn in Mid"); 
    } 
} 

class Bar extends Mid { 
    void fn() { 
     System.out.println("fn in Bar"); 
    } 

    void gn() { 
     Foo f = (Foo) this; 
     f.fn(); 
    } 
} 

public class Trial { 
    public static void main(String[] args) throws Exception { 
     Bar b = new Bar(); 
     b.gn(); 
    } 
} 

是否可以调用Foofn()?我知道我的解决方案gn()不起作用,因为this指向Bar类型的对象。

+0

这是甚至编译? – sll

+0

当然!问题是什么?? –

+0

我忽略了这些方法是私人的 – sll

回答

5

这在Java中是不可能的。您可以使用super,但它始终在类型层次结构中使用直接超类中的方法。

还要注意的是这样的:

Foo f = (Foo) this; 
f.fn(); 

polymoprhism 的非常清晰通话的虚拟工作:即使fFoo型的,但在运行时f.fn()被分派到Bar.fn()。编译时类型无关紧要。

相关问题