image.png

    1. //只有parcel4 及其子类 和 同包的类可以访问能访问PDestination,其他类都不能访问PDestination
    2. class Parcel4 {
    3. class PContents implements Contents {
    4. private int i = 11;
    5. public int value() { return i; }
    6. }
    7. protected class PDestination implements Destination {
    8. private String label;
    9. PDestination(String whereTo) {
    10. label = whereTo;
    11. }
    12. @Override
    13. public String realLabel() {
    14. return label;
    15. }
    16. }
    17. protected PDestination getPD(String s){ //19-20是为了下面的例子
    18. return new PDestination(s);
    19. }
    20. // destination方法的返回类型是接口类型,new出来的PDestination(s)不知道他的确切类型
    21. public Destination destination(String s) {
    22. return new PDestination(s);
    23. }
    24. public Contents contents() {
    25. return new PContents();
    26. }
    27. }
    28. public class TestParcel {
    29. public static void main(String[] args) {
    30. Parcel4 p = new Parcel4();
    31. Contents c = p.contents();
    32. //note--第四行的private去掉下面这行代码就不会报错: class PContents implements Contents
    33. //! Parcel4.PContents c1 = (Parcel4.PContents) c;
    34. Destination d = p.destination("Tasmania");
    35. // Illegal -- can't access private class:
    36. // Parcel4.PContents pc = p.new PContents();
    37. // Parcel4.PDestination pd = p.new PDestination("sasa");
    38. }
    39. }
    40. class Test extends Parcel4{
    41. public static void main(String[] args) {
    42. Test t = new Test();
    43. Parcel4 p4 = new Parcel4();
    44. Contents c = p4.contents();
    45. Parcel4.PDestination pd = p4.getPD("sss");
    46. pd.realLabel();
    47. }
    48. }
    49. class Test2{
    50. public static void main(String[] args) {
    51. Parcel4 p = new Parcel4();
    52. Parcel4.PDestination pd = p.getPD("sssas");
    53. }
    54. }