Think in java 答案_Chapter 5_Exercise 6

阅前声明: 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
  }
} 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值