테트리스 게임을 만들려고하는데 컴파일러 오류가 발생합니다.
Shape is not an enclosing class
객체를 만들려고 할 때
public class Test {
public static void main(String[] args) {
Shape s = new Shapes.ZShape();
}
}
각 모양에 내부 클래스를 사용하고 있습니다. 내 코드의 일부입니다
public class Shapes {
class AShape {
}
class ZShape {
}
}
내가 무엇을 잘못하고 있지 ?
답변
ZShape
정적이 아니므로 외부 클래스의 인스턴스가 필요합니다.
가장 간단한 해결책은 가능한 static
경우 ZShape 및 중첩 클래스를 만드는 것 입니다.
나는 또한 어떤 분야를 만들 final
거나 static final
당신도 할 수 있습니다.
답변
RetailerProfileModel이 기본 클래스이고 RetailerPaymentModel이 그 내부 클래스라고 가정하십시오. 다음과 같이 클래스 외부에서 Inner 클래스의 객체를 만들 수 있습니다.
RetailerProfileModel.RetailerPaymentModel paymentModel
= new RetailerProfileModel().new RetailerPaymentModel();
답변
내가 제안하는 것은 비 정적 클래스를 정적 클래스로 변환하지 않는 것입니다.이 경우 내부 클래스는 외부 클래스의 비 정적 멤버에 액세스 할 수 없기 때문입니다.
예 :
class Outer
{
class Inner
{
//...
}
}
따라서 이러한 경우 다음과 같은 작업을 수행 할 수 있습니다.
Outer o = new Outer();
Outer.Inner obj = o.new Inner();
답변
답변
때로는 부모 클래스의 전역 변수에 의존하기 때문에 정적 일 수없는 내부 클래스의 새 인스턴스를 만들어야 할 때가 있습니다. 이 상황에서 정적이 아닌 내부 클래스의 인스턴스를 작성하려고하면 not an enclosing class
오류가 발생합니다.
질문의 예를 들어, 클래스의 ZShape
전역 변수가 필요하기 때문에 정적 일 수 없다면 Shape
어떻게됩니까?
새 인스턴스를 ZShape
어떻게 만들 수 있습니까? 방법은 다음과 같습니다.
부모 클래스에서 getter를 추가하십시오.
public ZShape getNewZShape() {
return new ZShape();
}
다음과 같이 액세스하십시오.
Shape ss = new Shape();
ZShape s = ss.getNewZShape();
답변
Shape shape = new Shape();
Shape.ZShape zshape = shape.new ZShape();
답변
같은 문제가 발생했습니다. 모든 내부 공개 클래스에 대한 인스턴스를 작성하여 해결했습니다. 상황에 관해서는 내부 클래스 이외의 상속을 사용하는 것이 좋습니다.
public class Shape {
private String shape;
public ZShape zShpae;
public SShape sShape;
public Shape(){
int[][] coords = noShapeCoords;
shape = "NoShape";
zShape = new ZShape();
sShape = new SShape();
}
class ZShape{
int[][] coords = zShapeCoords;
String shape = "ZShape";
}
class SShape{
int[][] coords = sShapeCoords;
String shape = "SShape";
}
//etc
}
그런 다음 새 Shape ()를 수행 할 수 있습니다. shape.zShape를 통해 ZShape를 방문하십시오.