Package and access control permissions
Package definition
In Java, use the package keyword to define a package. This statement must be written on the first line of the xxx.java file.
Example: Definition package
package com.study.Demo; //定义程序所在包,此语句必须放在首行
public class Hello {
public static void main(String args[]){
System.out.println("Hello World");
}
}
Package import
Example: define a class
package com.study.A;
public class Message {
public void print(){
System.out.println("666");
}
}
Example: define another class, this class should use the previously defined class
package com.study.test;
import com.study.A.Message; //导入所需要的类
public class TestMessage {
public static void main(String args[]){
Message msg=new Message(); //实例化对象
msg.print(); //调用方法
}
}
//结果
//666
Example: Import multiple classes in a package
package com.study.test;
import com.study.A.*; //自动导入指定包中所需的类
public class TestMessage {
public static void main(String args[]){
Message msg=new Message();
msg.print();
}
}
If there is a conflict with the same name in different packages, you must add the package name when using the class.
Such as:
com.study.test.Message msg=new com.study.A.Message();
System common package
Access control authority
For the above table, it can be simply understood that
private can only be accessed in one class;
default can only be accessed in one package;
protected can be accessed in subclasses of different packages;
public is all.
For beginners, grasp the following two basic principles of access rights:
attribute declarations mainly use private declarations,
method declarations mainly use public declarations
Example:
package com.study.A;
public class A {
protected String info="Hello"; //使用protected权限定义
}
package com.study.Demo;
import com.study.A.A;
public class B extends A { //是A不同包的类
public void print(){
System.out.println("A类的info="+super.info); //直接访问父类中的protected属性
}
}
package com.study.Demo;
import com.study.Demo.B;
public class Test {
public static void main(String args[]){
new B().print();
}
}
//结果
//A类的info=Hello
Naming convention (although I am not very careful)
Class name: capitalization of each word at the beginning, for example: TestDemo;
variable name: capitalization of the first letter of the first word, capitalization of the first letter of each word thereafter, for example: studetName;
method name: the first letter of the first word Lowercase, capitalize the first letter of each word after it, for example: printInfo ();
constant name: capitalize each letter, for example: FLAG;
package name: lowercase all letters, for example: com.study