有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在具有私有构造函数的本地内部类的类之外创建实例?

考虑以下程序:

public class A
{
    public static void main(String[] args)
    {
        class B
        {
            private B()
            {
                System.out.println("local");
            }
        }
    // how are we able to create the object of the class having private constructor
    // of this class.
    B b1= new B();
    System.out.println("main");
    }
}

输出: 地方的 主要

一个拥有私有构造函数的类意味着我们只能在类内部创建对象,但这里我可以在类外部创建实例。有人能解释一下我们如何在B类之外创建B的对象吗


共 (4) 个答案

  1. # 1 楼答案

    您甚至可以访问该类的私有变量(试试!)

    这是因为您在调用该类的同一个类中定义该类,因此您拥有该类的私有/内部知识

    如果您将B类移动到A类之外,它将按预期工作

  2. # 2 楼答案

    请参阅JLS 6.6.1

    Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

    实现这一点的方法是使用合成的包保护方法

    “如果要隐藏内部类的私有成员,可以定义与公共成员的接口,并创建实现此接口的匿名内部类。请参阅this代码:”

    class ABC{
    private interface MyInterface{
        public void printInt();
    }
    
     private static MyInterface mMember = new MyInterface(){
     private int x=10;
    
        public void printInt(){
        System.out.println(String.valueOf(x));
     }
    };
    
     public static void main(String... args){
       System.out.println("Hello :: "+mMember.x); ///not allowed
       mMember.printInt(); // allowed
     }
    } 
    
  3. # 3 楼答案

    因为Top Level Class是一个幸福的家庭,每个人都可以互相接触,尽管private

    JLS 6.6.1

    6.6.1. Determining Accessibility

    • A member (class, interface, field, or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:
      • Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.
  4. # 4 楼答案

    你是这么说的
    A class having private constructor means we can create object inside the class only
    但是
    这是因为您在main(String[] args) method中定义了inner Class,而不是在Top Level Class中定义了inner Class

    如果你试试看

    public class A {
    
        class B {
            private B() {
                System.out.println("local");
            }
        }
    
        public static void main(String[] args) {
    
            B b1 = new B(); // you cant create object of inner Class B
            System.out.println("main");
        }
    }
    

    那么就不能创建内部类B的对象