Java 笔记分享 —— private 关键字

目录

1.1 前言

1.2 只能在同一类中访问

1.3 不能分配给外部类和接口

1.4 创建完全封装的类

1.5 总结


1.1 前言

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

1.2 只能在同一类中访问

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);
    }
}
运行结果:(报错)
    Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The field A.msg is not visible

1.3 不能分配给外部类和接口

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:

1.4 创建完全封装的类

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

1.5 总结

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值