Access control ( or implementation hiding) is about "not getting it right the first time."

refactoring

a primary consideration in object-oriented design is to "separate the thins that change from the thing that stay the same

To solve this problem, Java provides access specifiers: public, protected, package acess( which has no keyword), and private

package bundled the components together into a cohesive library unit. The acess specifiers are affected by whether a class is in the same package or in a seperate package.

package: the library unit

  a package contains a group of classes, organized together under a single namespace.

  The reason for all this importing is to provide a mechanism to manage namespaces.

  for example: cn.ada.util.testUtils 与 cn.bbs.util.testUtils

  the "unnamed" or default package

  When you create a source-code file for Java, it's commonly called a compilation unit ( sometimes a translation unit). Each compilation unit must have a name ending in .java, and inside the compilation unit there can be a public class that must have the same name as the file (including capitalization). The can be only one public class in each compilation unit.

  If there are additional classes in that compilation unit, they are hidden from the world outside that package because they're not public, and they comprise "support" classes for the main public class.

  Code organization

  When you compile a .java file, you get an output file for each class in the .java file.

  A working program is a bunch of .class files, which can be packaged and compressed into a Java Archive (JAR) file (using Java's jar archiver). The Java interpreter is responsible for finding, loading, and interpreting these files.

  If you want to say that all the components (each in its own separate .java and .class files) belong together, that's where the package keyword comes in.

  If you use a package statement, it must appear as the first non-comment in the file.

  Note that the convention for Java package names is to use all lowercase letters, even for intermediate words.

  What the package and import keywords allow you to do is to divide up the single global namespace so you won't have clashing names.

  Creating unique package names

  Since a package never really gets "packaged" into a single file, a package can be made up of many .class files, and things could get a bit clutters.

  To prevent this, a logical thing to do is to place all the .class files for a particular package into a single directory. This is one way that Java references the problem of clutter; you'll see the other way latter when the java utility is introduced.

  Collection the package files into a single subdirectory solves two other problems:

    1. creating unique package names

    2. finding those classes

  This is accomplished by encoding the path of the location of the .class file into the name of the package.

  By convention, the first part of the package name is the reversed Internet domain name of the creator of the class. Since Internet domain names are guaranteed to be unique.

  The Java interpreter proceeds as follows. First, it finds the environment variable CLASSPATH3 (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.)

  There's a variation when using JAR files, however. You must put the actual name of the JAR file in the classpath, not just the path where it's located.

  for example: CLASSPATH=.;D:\JAVA\LIB;D\JAVA\LIB\grape.jar

  Setting the CLASSPATH has been such a trial for beginning Java users (it was for me, when I started) that Sun made the JDK in later versions of Java a bit smarter. You’ll find that when you install it, even if you don’t set the CLASSPATH, you’ll be able to compile and run basic Java programs.

Collisions

  as long as you don't write the code that actually causes the collision, everything is OK--this is good, because otherwise you might end up doing a lot of typing to prevent collisions that would never happen.

  question: Vector exist in net.mindview.simple and java.util

      Vector v = new Vector(); //Collision, how to solve

  way 1: import net.mindview.simple.*;

       import java.util.*;

      java.util Vector v = new java.util.Vector(); // completely specifies the location of that Vector

  way 2: import net.mindview.simple.*;

      import java.util.Vector; //single-class import (don't use both colliding names in the same program

  A custom tool library

  static import的妙用

  import static new.mindview.util.Print.*; // 导入Print类中的static 属性和方法

  然后即可直接使用这些static属性和方法(不需要类名的限定)

  Using imports to change behavior

  You can accomplish this by changing the package that's imported in order to change the code used in your program form the debug version to the production version.

  Package caveat

  It's worth remembering that anytime you create a package, you implicitly specify a directory structure when you give the package a name.

  The package must live in the directory indicated by its name, which must be a directory that is searchable starting from the CLASSPATH.

Java access specifiers     

  Package access

  all the other classes in the current package have access to the member, but to all the classes outside of this package, the member appears to be private.

  Package access allows you to group related classes together in a package so that they can easily interact with each other.

  public: interface access

  The default package

  private: you can't touch that

  protected: inheritance access

  protected also gives package access—that is, other classes in the same package may access protected elements.

  protected: 在default package的基础,加了子类可以访问父类的属性或方法

Interface and implementation

  Wrapping data and methods within classes in combination with implementation hiding is often called encapsulation. The result is a data type with characteristics and behaviors.

  For clarity, you might prefer a style of creating classes that puts the public members at the beginning, followd by the protected, package-access, and private members. The advantage is that the user of the class can then read down from the top and see first what's important to them, and stop reading when they encounter the non-public members.

  Displaying the interface to the comsumer of a class is really the job of the class browser.

Class Access

  public and default package

  It is possible, though not typical, to have a compilation unit with no public class at all. In the case, you can name the file whatever you like.

  If a class that you're only using to accomplish the tasks performed by some public class in a package, and you think that sometime later you might want to completely change things and rip out your class altogether, subsitituting a different one. To accomplish this, you just leave the public keyword off the class, in which case it has package access (That class can be used only within that package.)

  When you create a package-access class, it still make sense to make the fields of the class private--you should always make fields as private as possible--but it's generally reasonable to give the methods the same access as the class (package access).

  Note that a class cannot to be private or protected.

  (Actually, an inner class can be private or protected, but that's a special case.)

  making all the constructors private, and create a static method that creates a new Object and return a reference to it. This can be useful:

    1. if you want to do some extra operations on the object before returning it

    2. if you want to keep count of how many objects to create. (如Singleton 单例模式)

  However, if a static member of the default package class is public, the client programmer can still access the static member even though they cannot create an object of that class.(实测,是不能访问)

Summary

  Notice that access control focuses on a relationship--and a kind of communication--between a library creator and the external clients of that library. There are many situations where this is not the case. For example, you are writing all the code yourself, or you are working in close quarters with a small team and everything goes into the same package. These situations have a different kind of communication, and rigid adherence to access rule may not be optimal. Default (package) access may be just fine.

  

Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(七)之Access Control的更多相关文章

  1. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(二)之Introduction to Objects

    The genesis of the computer revolution was a machine. The genesis of out programming languages thus ...

  2. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(六)之Initialization & Cleanup

    Two of these safety issues are initialization and cleanup. initialization -> bug cleanup -> ru ...

  3. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十三)之Strings

    Immutable Strings Objects of the String class are immutable. If you examine the JDK documentation fo ...

  4. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十四)之Type Information

    Runtime type information (RTTI) allow you to discover and use type information while a program is ru ...

  5. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十二)之Error Handling with Exceptions

    The ideal time to catch an error is at compile time, before you even try to run the program. However ...

  6. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十一)之Holding Your Objects

    To solve the general programming problem, you need to create any number of objects, anytime, anywher ...

  7. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十)之Inner Classes

    The inner class is a valuable feature because it allows you to group classes that logically belong t ...

  8. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(九)之Interfaces

    Interfaces and abstract classes provide more structured way to separate interface from implementatio ...

  9. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(八)之Polymorphism

    Polymorphism is the third essential feature of an object-oriented programming language,after data ab ...

随机推荐

  1. Mol Cell Proteomics. | 用于鉴定新型融合转录本及其在癌细胞中的潜在翻译产物的多功能蛋白质组基因组学工具FusionPro

    期刊:Molecular & Cellular Proteomics 发表时间:June 17, 2019 DOI:10.1074/mcp.RA119.001456 分享人:任哲 内容与观点: ...

  2. 树莓派3B+安装&卸载mysql

    需求 在树莓派上 安装Mysql 服务,并开启远程访问 步骤 安装 mysql server 1 $ sudo apt-get install mysql-server 我以为中间会让我提示输入 数据 ...

  3. P1361 小M的作物 【网络流】【最小割】

    题目描述 小M在MC里开辟了两块巨大的耕地A和B(你可以认为容量是无穷),现在,小P有n中作物的种子,每种作物的种子有1个(就是可以种一棵作物)(用1...n编号). 现在,第i种作物种植在A中种植可 ...

  4. 使用PostgreSQL注意事项

    一.大小写特别敏感 大写字段需要用“”引号(pg字段名使用“”,MySQL字段名使用``) ******表名以及字段名如果是小写但是为关键字,比如name,则也需使用"": 二.分 ...

  5. 从源码学习Java并发的锁是怎么维护内部线程队列的

    从源码学习Java并发的锁是怎么维护内部线程队列的 在上一篇文章中,凯哥对同步组件基础框架- AbstractQueuedSynchronizer(AQS)做了大概的介绍.我们知道AQS能够通过内置的 ...

  6. TensorFlow v2.0实现Word2Vec算法

    使用TensorFlow v2.0实现Word2Vec算法计算单词的向量表示,这个例子是使用一小部分维基百科文章来训练的. 更多信息请查看论文: Mikolov, Tomas et al. " ...

  7. Math对象常用方法介绍

     <script>         /* 001-Math.abs()  绝对值 */         console.log(Math.abs(123), Math.abs(-998), ...

  8. 《java编程思想》对象导论

    1.抽象过程 所有编程语言都提供抽象机制.可以认为,人们所能够解决的问题的复杂性直接取决于抽象的类型和质量,所谓的'类型'是指“所抽象的是什么?”汇编语言是对底层机器的轻微抽象. java的基本 特性 ...

  9. 吴恩达DeepLearning.ai的Sequence model作业Dinosaurus Island

    目录 1 问题设置 1.1 数据集和预处理 1.2 概览整个模型 2. 创建模型模块 2.1 在优化循环中梯度裁剪 2.2 采样 3. 构建语言模型 3.1 梯度下降 3.2 训练模型 4. 结论   ...

  10. [POI2014][树形DP]FarmCraft

    题目 In a village called Byteville, there are houses connected with N-1 roads. For each pair of houses ...