Modifier Class Package Subclass World public YYYY protected YYYN no modifier YYNN private YNNN public class a { protected int x; } public class b { b() { a A=new a(); Ax=9;//why we can access this field ? } } 请帮助我了解Java中受保护的具体工作
我想对此进行一些讨论,但我无法推断出我的案例的答案。 仍然需要帮助。 这是我的代码: package JustRandomPackage; public class YetAnotherClass{ protected int variable = 5; } package FirstChapter; import JustRandomPackage.*; public class ATypeNameProgram extends YetAnotherClass{ public static void main(String[] args) { YetAnotherClass bill = new YetAnotherClass(); System.out.println(bill.variable); // error: YetAnotherClass.variable is not visible } } 一些定义之后,上面的例子似乎令人困惑: 1. Subclass is a class that extends another class. 2. Class […]
package packageOne; public class Base { protected void display(){ system.out.println(“in Base”); } } package packageTwo; public class Derived extends packageOne.Base{ public void show(){ new Base().display();//this is not working throws compilation error that display() from the type Base is not visible new Derived().display();//is working display();//is working } } 这两个包有两个不同的文件。 但为什么会这样呢?