先引用某本书上的一个表格(阉割版):
# | Outter class / Interface | Member properties | Method | Constructor |
---|---|---|---|---|
public | yes | yes | yes | yes |
protected | no | yes | yes | yes |
private | no | yes | yes | yes |
abstract | yes | no | yes | no |
final | yes | yes | yes | no |
static | no | yes | yes | no |
friendly | yes | yes | yes | yes |
- private: 当前类访问权限(只能在当前类中使用)
- friendly: 包访问权限(同一个包可以互相访问)
- protected: 子类访问权限(要被子类继承的可以使用此修饰符修饰)
- public: 公共访问权限(全局访问内可以访问)
ps:friendly特指包访问权限
另外:
如果我们希望所定义的类从属于一个群组,就可以使用关键字package。使用它的时候必须写在文件的中除注释以外的第一行。如:
package cn.zhou;
public class MyClass{
private String zhouchaoyuan;
}
而当使用到另一个群组里面的类时我们可以用import关键导入,如果使用常量我们还可以静态导入,使用import static,如:
import java.util.ArrayList;//使用java.util包下的ArrayList
import static java.lang.Math.*;//使用Math包下的所有static修饰的方法和属性
即可直接:
ArrayList list=new ArrayList();
System.out.println(sin(PI/2));
利用反射突破访问权限
package com.example;
import java.lang.reflect.Field;
/**
* Created by zhouchaoyuan on 16/7/19.
*/
public class ReflectTest {
public static void main(String[] args) {
try {
Class<?> obj = Class.forName("com.example.Person");
Field[] f = obj.getDeclaredFields();
for(Field field : f){
field.setAccessible(true);//设置为可访问
System.out.println(field.getName()+":"+field.get(obj.newInstance()));
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Person{
private String name = "cross";
}