详解java中private关键字的使用方法
内容摘要
private 关键字中文就是私有关键字,那么到底要怎么使用呢?1、只能在同一类中访问class A {
private String msg="Try to access the private variable outside the class"
private String msg="Try to access the private variable outside the class"
文章正文
private 关键字中文就是私有关键字,那么到底要怎么使用呢?
1、只能在同一类中访问
1 2 3 4 5 6 7 8 9 10 | class A { private String msg= "Try to access the private variable outside the class" ; // 用 private 修饰,无法别的类调用,只能在这个类中被调用 } public class PrivateExample { public static void main(String[] args) { A a= new A(); System.out.println(a.msg); } } |
推荐教程:java快速入门
1 2 3 | 运行结果:(报错) Exception in thread "main" java.lang.Error: Unresolved compilation problem: The field A.msg is not visible |
2、不能分配给外部类和接口
1 2 3 4 5 6 7 8 9 | private class PrivateExample { // private 是不能用来修饰类的 void display(){ System.out.println( "Try to access outer private class" ); } public static void main(String[] args) { PrivateExample3 p= new PrivateExample(); p.display(); } } |
1 2 | 运行结果:(报错) Exception in thread "main" java.lang.Error: Unresolved compilation problem: |
3、创建完全封装的类
private关键字的最佳用法是通过使该类的所有数据成员变为私有来在Java中创建一个完全封装的类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import java.lang.reflect.Method; class A { private void display() { System.out.println( "private method is invoked" ); } } public class PrivateExample { public static void main(String[] args)throws Exception { Class c = Class.forName( "A" ); // 加载 A 类 Object o= c.newInstance(); // 实例化对象 Method m =c.getDeclaredMethod( "display" , null); // getDeclaredMethod方法返回指定方法,"display" 就是指定方法,null 表示该方法的参数 m.setAccessible(true); // setAccessible 方法能在运行时压制 Java 语言访问控制检查,从而能任意调用被私有化保护的方法 ( Method ),域 ( Field )、构造方法 m.invoke(o, null); // invoke方法来执行对象的某个方法,括号中的 o 是方法,null 是参数 } } |
1 2 | 运行结果: private method is invoked |
相关视频教程推荐:java视频教程
代码注释
[!--zhushi--]