Tag: code specifies default visibility. SH Engineer Strong Object Stat
One, Java access modifier
Access modifiers to control the visibility of members in a class
There are four access modifiers, respectively: default,private,public,protected
1, default: No write modifiers are required by default. can only be accessed within the same package.
2. Private: can only be accessed in the same class.
3, public: can be accessed from anywhere
4. Protected (Protected): Used in inheritance of class
Second, package packages
In large projects, there will often be dozens of or even hundreds of classes, if the class is not classified management, late maintenance will be a great inconvenience.
Therefore, classes (or other types) need to be categorized and managed, a mechanism called "packages".
A "package" is a container for classes that separates class name spaces. If you do not specify a package name, all examples belong to a default unnamed package.
To access the class in different packages, import the package imports
As below, define a new job class and place the job class inside the study package
package study; // Defining Study Packages Public class Job { // package defines the job class public String jobName; Public void Show () { System.out.println (jobName); }}
Then, when accessing the job class in the package, import imports the job class in the study package:
Import Study. Job; // Import the Job class in study Public class MyTest { publicstaticvoid main (string[] args) { Job myJob =new Job (); // instantiating the job class Myjob.jobname= "Engineer"; // invoking the member properties of a class Myjob.show (); // calling a member method of a class }}
Output Result:
Engineer
Further explanation: According to the method of importing package class above, if the study package defines n waste class, then each instantiation of a non-homogeneous object, you need to write import study.xxxx, if there are 100 classes will write 100 times import, more trouble
We can import all the classes in the package at once by using the asterisk * instead of all the class names in the package--Importstudy.*
import study.*; // Import all classes in a study package at once Public class MyTest { publicstaticvoid main (string[] args) { Job MyJob=new Job (); Myjob.jobname= "Engineer"; Myjob.show (); }}
Note:
The classes in the same package not only represent them in the same containment, but also in the same physical path.
When defining class, it is recommended that you set the package as much as possible and not in the default packages.
Access modifiers and packages in Java