在做入学测试题,发现自己写的类的构造函数居然不能被访问,后来才发现,必须用public修饰一下。但是不是说默认权限在一个包内可以访问的么?为什么一定要用public修饰才行?我试了protected也不行,这是什么原理? 
- package com.itheima;
 
  
- import java.lang.reflect.Constructor;
 
  
- /**
 
 -  * 第8题:编写一个类,增加一个实例方法用于打印一条字符串。并使用反射手段创建该类的对象, 并调用该对象中的方法。
 
 -  * @author A
 
 -  *
 
 -  */
 
 - public class Test8 {
 
  
-         public static void main(String[] args) {
 
 -                 //调用class字节码文件的方法使用无参的构造函数创建实例,并调用print方法
 
 -                 try {
 
 -                         PrintClass.class.newInstance().print("www.itheima.com");
 
 -                 } catch (InstantiationException | IllegalAccessException e) {
 
 -                         throw new RuntimeException("类名错误!");
 
 -                 }
 
 -                 //当然,也可以先通过class的字节码文件得到构造方法,然后使用构造方法的newInstance方法创建实例,再调用。
 
 -                 try {
 
 -                         Constructor constructor = PrintClass.class.getConstructor();
 
 -                         PrintClass pc = (PrintClass)constructor.newInstance();
 
 -                         pc.print("Hellow itheima!");
 
 -                 //这里异常太多了,为了方法观看,就先一起处理了。
 
 -                 } catch (Exception e){
 
 -                         throw new RuntimeException("获取构造方法或创建实例失败。");
 
 -                 }
 
 -         }        
 
 - }
 
  
- //创建一个类
 
 - class PrintClass{
 
 -         //空参数的构造方法
 
 -         public PrintClass(){}
 
 -         //实例方法:打印传入的字符串。
 
 -         public void print(String str){
 
 -                 System.out.println(str);
 
 -         }
 
 - }
 
  复制代码 |   
        
 
    
    
    
     
 
 |