Wednesday, January 21, 2015

[Java]Access Control


The article is mainly the summary of book "Thinking in Java" from Page 209 to Page 235.

Package:
  1. A package is a group of class, organised together under a single namespace.
  2. Actually, package is kind of similar to namespace in C++, if we want to use the object in one package, take java.util.ArrayList as example,  we can use java.util.ArrayList list = new java.util.ArrayList(),  just like std::vector in C++, or we can use import java.util.ArrayList, like using namespace std in  C++.
  3. The file organisation is representation by the package name, when we import a package, the java interpreter will go to the CLASSPATH, then we go to subdirectory as shown in the name of package CLASSPATH/java/util/ and looking for the class we want to use. The CLASSPATH contains the package individual created and also the library, such as jar files.
  4. There may be name collision if two package contains same name and we want to use them, in this case, we can import one and use the full name of the other one.
  5. Use static import we can use the static method of that class without use the class name to access that method.
Java access specifiers:
  1. Using public keyword before a member declaration, the member is available to everyone. 
  2. Using no keyword before a member declaration, the member has the package access, that is, all the other classes in the current package have access to that member, but to all the classes outside of this package, the member appears to be private, also in the base class and derived class are in the same package, the derived can access those methods.
  3. Using private keyword before a member declaration means no one can access that member except the class that contains that member, inside method of that class.
  4. Using protected keyword before a member declaration, the subclass of that base class can access that member,  also it has package access, other class in the same package can access the member
  5. Using public keyword before a class, the class can be created and used everywhere.
  6. Using no keyword before a class, the class can only be used and create in this package, cannot be used outside of the package.
  7. Except for the inner class, we can not use protected or private keywords before a class.

No comments:

Post a Comment