我想用getX方法获取x并在其他类中使用它,但是eclipse说我的方法应该是静态的,但我不想使其静态化。
public abstract class Shape {
private int x;
private Color color;
public Shape (int x, Color color) {
this.x = x;
this.color = color;
}
public abstract void draw();
public Color getColor() {
return color;
}
public int getX() { //here here here
return x;
}
}
public class Square extends Shape {
public Square(int x, Color color) {
super(x, color);
}
public void draw() {
for(int i = 0; i < Shape.getX(); i++) {// here is a problem
System.out.print(" ");
}
if (getColor() == Color.BLACK)
System.out.println("[]");
if (getColor() == Color.RED)
System.err.println("[]");
}
}
我想使其可执行。
答案 0 :(得分:0)
您正在尝试以静态方式访问非静态方法。如下所示,使用getX()代替Shape.getX(),
public class Square extends Shape {
public Square(int x, Color color) {
super(x, color);
}
public void draw() {
for(int i = 0; i < getX(); i++) {// here is a problem
System.out.print(" ");
}
if (getColor() == Color.BLACK)
System.out.println("[]");
if (getColor() == Color.RED)
System.err.println("[]");
}
}