Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(七)之Access Control
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的更多相关文章
- 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 ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(六)之Initialization & Cleanup
Two of these safety issues are initialization and cleanup. initialization -> bug cleanup -> ru ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十三)之Strings
Immutable Strings Objects of the String class are immutable. If you examine the JDK documentation fo ...
- 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 ...
- 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 ...
- 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 ...
- 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 ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(九)之Interfaces
Interfaces and abstract classes provide more structured way to separate interface from implementatio ...
- Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(八)之Polymorphism
Polymorphism is the third essential feature of an object-oriented programming language,after data ab ...
随机推荐
- Mol Cell Proteomics. | Elevated Hexokinase II Expression Confers Acquired Resistance to 4-Hydroxytamoxifen in Breast Cancer Cells(升高的己糖激酶II表达使得乳腺癌细胞获得对他莫昔芬的抗性)(解读人:黄旭蕾)
文献名:Elevated Hexokinase II Expression Confers Acquired Resistance to 4-Hydroxytamoxifen in Breast Ca ...
- JavaScript 模式》读书笔记(4)— 函数1
从这篇开始,我们会用很长的章节来讨论函数,这个JavaScript中最重要,也是最基本的技能.本章中,我们会区分函数表达式与函数声明,并且还会学习到局部作用域和变量声明提升的工作原理.以及大量对API ...
- Spring Cloud 系列之 Alibaba Sentinel 服务哨兵
前文中我们提到 Netflix 中多项开源产品已进入维护阶段,不再开发新的版本,就目前来看是没有什么问题的.但是从长远角度出发,我们还是需要考虑是否有可替代产品使用.比如本文中要介绍的 Alibaba ...
- Django redis的使用
一 简介 redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合).zset(sorted ...
- 正则表达式(R&Python)
regular expression 1.R,strongly recommend this blog The table_info examples are following: du_mtime_ ...
- Node.js安装过程
今天电脑的node用不了了,于是决定重新安装一下 一.安装Node.js 1.首先,可以直接去Node的官网寻找适合自己电脑系统的版本 官网地址:https://nodejs.org/en/downl ...
- UVA - 11426 欧拉函数(欧拉函数表)
题意: 给一个数 N ,求 N 范围内所有任意两个数的最大公约数的和. 思路: f 数组存的是第 n 项的 1~n-1 与 n 的gcd的和,sum数组存的是 f 数组的前缀和. sum[n]=f[1 ...
- ORA-01017的一种情况:sysdba可以登录,normal不可登录
在arcCatalog中创建完sde数据库之后,用PLSQL登录提示只能用SYSDBA登录. 用户名:sde 密码:123456 数据库:ORCLZLL 连接为:Normal 点击登录 ...
- Selenium系列(十五) - Web UI 自动化基础实战(2)
如果你还想从头学起Selenium,可以看看这个系列的文章哦! https://www.cnblogs.com/poloyy/category/1680176.html 其次,如果你不懂前端基础知识, ...
- return console.log()结果为undefined现象的解答
console.log总是出现undefined--麻烦的console //本文为作者自己思考后总结出的一些理论知识,若有错误,欢迎指出 bug出现 需求如下:新建一个car对象,调用其中的de ...