private keyword in Chinese is a private keyword, so how to use it?
1. It can only be accessed in the same category
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); } }
Recommended tutorial: java quick start
运行结果:(报错) Exception in thread "main" java.lang.Error: Unresolved compilation problem: The field A.msg is not visible
2. Cannot be assigned to external classes and interfaces
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(); } }
运行结果:(报错) Exception in thread "main" java.lang.Error: Unresolved compilation problem:
3. Create a fully encapsulated class
The best use of the private keyword is by making the class All data members are made private to create a fully encapsulated class in Java.
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 是参数 } }
运行结果: private method is invoked
Recommended related video tutorials: java video tutorial
The above is the detailed content of Detailed explanation of how to use the private keyword in java. For more information, please follow other related articles on the PHP Chinese website!