2017-05-25 62 views
-2

我的程序如下:不能夠訪問受保護的字段或方法在子調用

package pack1; 

public class Parent { 
int i=0; 
protected j =1; 
public k = 2; 
} 

package pack2; 

import pack1.Parent; 
public class Child extends Parent { 

public static void main (String args[]) { 
    Child c1 = new Child(); 
    c1.j = 100; // This is working fine 

    Parent c2 = new Child(); 
    c2.j=200; // Compilation error 

} 
} 

我的問題是:爲什麼我們也不能夠與「C2」訪問保護成員在父類。

+0

爲什麼你在包之間有繼承?你應該重新考慮你的項目結構。 – Guy

回答

0

不能與被爭論的答案爲「是因爲規範是這麼說的」:

A protected member of a base class is accessible in a derived class only if the access occurs through the derived class type. 

,你將不得不作出成員內部(或公共)。