2011-07-06 130 views
3

我在下面的代碼與Eclipse IDE中寫道:如何在無關的類中訪問受保護的方法?

public interface X 
{ 
    final public static int SOME_CONST = 0; 
} 
public class Handle implements X 
{ 
    protected void methodHandle() { } 
//... 
} 

public class User implements X 
{ 
    Handle handle = new Handle(); 
    private void methodUser() 
    { 
    Y y = new Y() // anonymous inner class 
    { 
     public void methodY() 
     { 
     handle.methodHandle(); // <--- why this is NOT giving error ? 
     } 
    } 
    } 
} 

即使Handle.methodHandle()protected,它仍然從調用一個匿名內部class方法的內部方法?爲什麼會發生,我錯過了什麼? HandleUser之間的唯一關係是它們是implement相同的X

回答

6

如果兩個類都在同一個包中,則可以調用受保護的方法。

有關更多詳細信息,請參見this

2

如果調用類在同一個包中,它將能夠調用受保護的方法。如果這不是你想要的,你應該讓你的方法是私人的。

1

同一包中的類不是'不相關的'。

+0

+1是的,他們確實不是「不相關的」。 – iammilind

相關問題