我收到此错误:
线程“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/