java - 没有封闭实例的分配引发了异常

标签 java

我收到此错误:

线程“main”java.lang.Error中出现异常: Unresolved 编译问题:

No enclosing instance of type PrimitiveCasting is accessible. Must qualify the allocation with an enclosing instance of type PrimitiveCasting (e.g. x.new A() where x is an instance of PrimitiveCasting).

No enclosing instance of type PrimitiveCasting is accessible. Must qualify the allocation with an enclosing instance of type PrimitiveCasting (e.g. x.new A() where x is an instance of PrimitiveCasting).


at casting.PrimitiveCasting.main(PrimitiveCasting.java:22)

封装类型转换​​;

public class PrimitiveCasting {
    class anand {
        int a = 90;

        void anand1() {
            System.out.println("anand is having anand1");
        }
    }

    class babu extends anand {
        int c, b = 88;

        void babu1() {
            System.out.println("babu is having babu1");
        }
    }

    public static void main(String[] args) {
        System.out.println("**********");
         anand z1= new anand();
         z1.anand1();

         babu b1= new babu();
         b1.anand1();
         b1.babu1();`enter code here`
         System.out.println("********");
    }

}

最佳答案

这是正常的,在您的代码中,您将 anand 类定义为与 PrimitiveClass 的实例绑定(bind),即,您可以从 PrimitiveClass 的实例获得 anand 类的实例。这就是我们所说的内部类。 为了使您的代码正常工作,您可以将 anand (和 babu1)类标记为静态。 这是代码:

public class PrimitiveCasting {
static class anand {
    int a = 90;

    void anand1() {
        System.out.println("anand is having anand1");
    }
}

static class babu extends anand {
    int c, b = 88;

    void babu1() {
        System.out.println("babu is having babu1");
    }
}

public static void main(String[] args) {
    System.out.println("**********");
     anand z1= new anand();
     z1.anand1();

     babu b1= new babu();
     b1.anand1();
     b1.babu1();
     System.out.println("********");
}

}

或者您可以创建 PrimitiveClass 的实例,然后实例化 anand 或 babu,如下所示:

public class PrimitiveCasting {
class anand {
    int a = 90;

    void anand1() {
        System.out.println("anand is having anand1");
    }
}

class babu extends anand {
    int c, b = 88;

    void babu1() {
        System.out.println("babu is having babu1");
    }
}

public static void main(String[] args) {
    System.out.println("**********");
    PrimitiveCasting primitiveCasting = new PrimitiveCasting();
    anand z1= primitiveCasting.new anand();
    z1.anand1();

    babu b1= primitiveCasting.new babu();
    b1.anand1();
    b1.babu1();
    System.out.println("********");
}

}

希望这有帮助!

关于java - 没有封闭实例的分配引发了异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38201038/

相关文章:

java - KeyListener 仅有时有效

java - 如果计算机关闭,由 java 应用程序创建的 XML 文件的内容将消失

java - 我很困惑的简单Java数组语法

java - WsImport ant 任务和 JDK 6

java - 为什么在Java 9中不推荐使用finalize()方法?

java - 在构造函数(java)中查询数据库?

java - 如何阻止 Proguard 收缩删除注释参数,即使它保留注释本身?

java - Hashmap get 返回 null

java:符号查找错误: undefined symbol :_ZN2cv6String8allocateEm

java - Hazelcast 映射值序列化异常