详解java中private关键字的使用方法

王林
王林 转载
2020-03-13 18:03:26 6389浏览

private 关键字中文就是私有关键字,那么到底要怎么使用呢?

1、只能在同一类中访问

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快速入门

运行结果:(报错)
    Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The field A.msg is not visible

2、不能分配给外部类和接口

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、创建完全封装的类

private关键字的最佳用法是通过使该类的所有数据成员变为私有来在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

相关视频教程推荐:java视频教程

以上就是详解java中private关键字的使用方法的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:csdn,如有侵犯,请联系admin@php.cn删除