Java编程思想(第四版)学习笔记(7)

2016-07-22  本文已影响0人  FreeCode

第六章 访问权限控制


1.访问权限控制的等级
2.包:库单元

Java用package关键字将构件捆绑到一个内聚的类库单元中。当编写一个Java源代码文件时,此文件通常被称为编译单元(有时也被称为转译单元)。每个编译单元必须有一个后缀名.java,而在编译单元内则可以有一个public类,该类的名称必须与文件的名称相同(包括大小写,但不包括文件的后缀名.java)。每个编译单元只能有一个public类,否则编译器就不会接受。如果在该编译单元之中还有额外的类的话,那么在包之外的世界是无法看到这些类的,这是因为它们不是public类,而且它们主要用来为主public类提供支持。

Java解释器的运行过程如下:
The Java interpreter proceeds as follows. First, it finds the environment variable CLASSPATH (set via the operating system, and sometimes by the installation program that installs Java or a Java-based tool on your machine). CLASSPATH contains one or more directories that are used as roots in a search for .class files. Starting at that root, the interpreter will take the package name and replace each dot with a slash to generate a path name off of the CLASSPATH root (so package foo.bar.baz becomes foo\bar\baz or foo/bar/baz or possibly something else, depending on your operating system). This is then concatenated to the various entries in the CLASSPATH. That’s where it looks for the .class file with the name corresponding to the class you’re trying to create. (It also searches some standard directories relative to where the Java interpreter resides.)

3.Java访问权限修饰词

访问权限修饰词可以类中每个成员的定义之前(无论它是一个域还是一个方法)。

包访问权限

取得对某个成员的访问权的唯一途径是:

访问权限示意图
4.接口和实现
public class OrganizedByAccess {
  public void pub1() { /* ... */ }
  public void pub2() { /* ... */ }
  public void pub3() { /* ... */ }
  private void priv1() { /* ... */ }
  private void priv2() { /* ... */ }
  private void priv3() { /* ... */ }
  private int i;
  // ...
}
5.类的访问权限
class Soup1 {
  private Soup1() {}
  // (1) Allow creation via static method:
  public static Soup1 makeSoup() {
    return new Soup1();
  }
}

class Soup2 {
  private Soup2() {}
  // (2) Create a static object and return a reference
  // upon request.(The "Singleton" pattern):
  private static Soup2 ps1 = new Soup2();
  public static Soup2 access() {
    return ps1;
  }
  public void f() {}
}

// Only one public class allowed per file:
public class Lunch {
  void testPrivate() {
    // Can't do this! Private constructor:
    //! Soup1 soup = new Soup1();
  }
  void testStatic() {
    Soup1 soup = Soup1.makeSoup();
  }
  void testSingleton() {
    Soup2.access().f();
  }
}

说明
1)如果想要在返回引用前在Soup1上做一些额外的工作,或是如果想要记录到底创建了多少个Soup1对象(可能与限制其数量),这种做法将会大有裨益的。
2)Soup2用到了单例模式(singleton),这是因为我们始终只能创建它的一个对象。

上一篇 下一篇

猜你喜欢

热点阅读