"Java programming ideas" 06. Access Control

  • How things change and things remain the same distinction
  • Access to the control level (large -> Small): public, protected, package access (no keyword), private

Package: the library unit

Code Organization

  • Compile a .java file, each class will have an output file .class, the same file name and class name
  • Java can run the program is a set of Java packaged and compressed into a document file ( JAR) .class files. Java interpreter is responsible for finding these files, loading and interpretation
  • Indeed library --- ---> a set of classes in the evening
  • Java package naming all lowercase letters
package access.mypackage;
public class MyClass{ /* ... */ }

Use import to access the names of available

import access.mypackage.MyClass

Create a unique package name

  • The first part of the package name: the creator of the class of Internet domain name in reverse order

Thinking:条件编译

Java access modifiers

Package access

  • Default access (no keywords)
  • Sometimes also denoted friendly
    class for a package with:
The current package for all other classes All classes other than the package
Have access Equivalent to the private

Way to get access to a member of the

  • The members of the public to change
  • Members without qualifiers & placed in other classes in the same package
  • Inheritance - can access public members, protected members
  • Providing access to its (the accessor) and variation device (mutator) - get / set method

public: Interface Access

private: You can not access

Generally considered that those members of the public want to clear the client programmer, so they are declared public, but initially you may not think you will often need to use private, because without it, can still work . However, it soon proved that the use of private of how important it is, especially in multi-threaded.

  • Any method can certainly just a class of "helper" method, it can be designated as private, will not ensure that other places in the package of misuse

protected: inheritance access

Interface and implementation

Access control -> concrete realization of hiding, encapsulation

  • Setting up the Client programmers can use and not use borders
  • Interface and embodied separation

Access class

  • For access to the class, only two choices: package access or public

to sum up

  • Two reasons to control access to members of:
    • So that users do not touch those parts should not be touched
    • Let the library designer to change the internal workings of the class

    Open for extension, closed for modification

When has the ability to change the underlying implementation details, not only free to improve the design, may also free to make mistakes, when you learned that mistakes are relatively safe when you can more confidently experiment, it can be learn faster and faster completion of projects

Guess you like

Origin www.cnblogs.com/hhhqqq/p/12588175.html