-1

I want to get x with getX method and use it in other class, but eclipse says that my method should be static, but I don't want to make it static.

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("[]");
    }
}

I want to make it executable.

tobsob
  • 602
  • 9
  • 22
Panki
  • 1
  • 1
  • 2
    Just use `getX()` or `this.getX()` instead of `Shape.getX()`. Remember, `getX()` is an instance method of `Shape`, `Square` extends `Shape`, and you're attempting to call `getX()` from "inside" an instance of `Square`. Note you're already doing the correct thing for `getColor()`. – Slaw Sep 26 '19 at 10:48
  • replace Shape.getX() -> getX(). You don't need to specify class you have that method in your instance – Veselin Davidov Sep 26 '19 at 10:49

1 Answers1

0

You are trying to access non static method in static way. Use getX() instead of Shape.getX() as below,

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("[]");
    }
}
madhepurian
  • 271
  • 1
  • 13