现在的位置: 首页 > 综合 > 正文

Think in java 答案_Chapter 5_Exercise 6

2013年10月11日 ⁄ 综合 ⁄ 共 1942字 ⁄ 字号 评论关闭

阅前声明: http://blog.csdn.net/heimaoxiaozi/archive/2007/01/19/1487884.aspx

/****************** Exercise 6 ******************
* Create a class with public, private,
* protected, and "friendly" data members and
* method members. Create an object of this class
* and see what kind of compiler messages you get
* when you try to access all the class members.
* Be aware that classes in the same directory
* are part of the "default" package.
***********************************************/

package c05;
public class E06_AccessControl {
  public int a;
  private int b;
  protected int c;
  int d; // "Friendly"
  public void f1() {}
  private void f2() {}
  protected void f3() {}
  void f4() {} // "Friendly"
  public static void main(String args[]) {
    E06_AccessControl test =
      new E06_AccessControl();
    // No problem accessing everything inside
    // of main() for this class, since main()
    // is a member and therefore has access:
    test.a = 1;
    test.b = 2;
    test.c = 3;
    test.d = 4;
    test.f1();
    test.f2();
    test.f3();
    test.f4();
  }

//+M java c05.E06_AccessControl

**You can see that main( ) has access to everything because it’s a member. If you create a separate class within the same package, that class cannot access the private members:

// A separate class in the same package cannot
// access private elements:
package c05;
public class E06_Other {
  public E06_Other() {
    E06_AccessControl test =
      new E06_AccessControl();
    test.a = 1;
    //! test.b = 2; // Can't access:  private
    test.c = 3;
    test.d = 4;
    test.f1();
    //! test.f2(); // Can't access:  private
    test.f3();
    test.f4();
  }
}

**If you create a class in a separate package (which you can do either by explicitly giving a package statement, or by simply putting it in a different directory) then it is unable to access anything but public members:

// A separate class in the same package cannot
// access private elements:
package c05.other2;
public class E06_Other2 {
  public E06_Other2() {
    c05.E06_AccessControl test =
      new c05.E06_AccessControl();
    test.a = 1;
    //! test.b = 2; // Can't access: private
    //! test.c = 3; // Can't access: protected
    //! test.d = 4; // Can't access: friendly
    test.f1();
    //! test.f2(); // Can't access:  private
    //! test.f3(); // Can't access: protected
    //! test.f4(); // Can't access: friendly
  }
} 


 

抱歉!评论已关闭.