"Java Programming Thought" Notes Chapter 6 Access Control

1. Compilation unit

  • There can only be one public class in a compilation unit, that is, a .java file, and the file name must be exactly the same as the public class name.
  • There can also be no public class file name in the compilation unit.

2. Package: Library Unit

2.1 The default access permission is the package access permission, which can be accessed under the same package (meaning that the package access permission classes or class members in each .java file in the same directory can access each other).

2.2 Parent and subdirectories do not belong to the same package (in fact, there is no parent and subdirectory, and the package names are all unique).

2.3 A package can be regarded as a collection of classes, including public classes and default permission classes, so two .java files under the same package cannot have classes with the same name.

2.4 To use classes in other packages, you need to import packages

3. Permissions from large to small

  •  public protected package access private

3.1 Public interface access rights

3.2 protected inherited access rights and package access rights , no public rights.

3.3 private cannot be accessed Only the class where the private member is located can access .

3.4 Making all constructors private prevents objects from being created by new outside the class.

4. Class permissions

  • Classes only have public and default package permissions, and inner classes can have protected and private permissions.

5. Access control is also called the hiding of specific implementations

6. Packaging

  •  Packing data and methods into classes, and hiding of concrete implementations.

7. Class Access

  • For a class , its internal members have no mutual rights, and calling a method does not require an object and this 
class Test {
	private void f() {
		
	};

	void g() {
		
		f();
	};
}

8. Objects of this class cannot be generated outside the private constructor 

  • The Test object cannot be generated outside the private constructor, but the object of the class can be returned through the static method inside the class, so that the Test object can be created externally
public class ClassRe {

	public static void main(String[] args) {
		Test p1 = Test.make(),
			 p2 = Test.make();
		System.out.println(p1);
		System.out.println(p2);

	}

}

class Test {
	private Test() {};

	static Test make() {

		return new Test();
	}
}
From the output, 2 different objects are created
lpkiebfe.Test@62efae3b
lpkiebfe.Test@6597d63b

9. Singleton

class Test {
	private Test() {};

	private static Test t1 = new Test(); //only one object is created
	
	public static Test access(){ //External can only create Test objects by calling this method
		return t1;
	}
}


.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325401714&siteId=291194637