Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The method *****is undefined for the type***** in Java

I'm trying to call a method from an abstract class Sprite in another package, but I got "The method getSymbol() is undefined for the type Sprite"

Here's the code.

public class ArrayGrid<Sprite> implements Grid<Sprite> {

  private int numRows;
  private int numColumns;
  private Sprite[][] grid;
  @SuppressWarnings("unchecked")
  public ArrayGrid(int numRows, int numColumns) {
    this.numRows = numRows;
    this.numColumns = numColumns;
    this.grid = (Sprite[][]) new Object[numRows][numColumns];
  }

  @SuppressWarnings("unchecked")
  @Override
  public boolean equals(Object other) {
    if (this.getClass().equals(other.getClass())) {
      if (this.numRows == ((ArrayGrid<Sprite>) other).numRows
          && this.numColumns == ((ArrayGrid<Sprite>) other).numColumns) {
        for (int i = 0; i < this.numRows; i++) {
          for (int j = 0; j < this.numColumns; j++) {
            if (this.getCell(i, j).getSymbol() == ((ArrayGrid<Sprite>) other).getCell(i, j).getSymbol()) { // <<<<< the error is here
              return true;
            }
          }
        }
        return true;
      }
    }
    return false;
  }

And here is the code from another package sprites

public abstract class Sprite {

  protected char symbol;
  protected int row;
  protected int column;

  public Sprite(char symbol, int row, int column) {
    this.symbol = symbol;
    this.row = row;
    this.column = column;
  }

  public char getSymbol() {
    return symbol;
  }

I guess the problem is that the method from an abstract class cannot be instantiated.

But I don't know how to fix it.

like image 698
Mingyu Chen Avatar asked Dec 19 '22 23:12

Mingyu Chen


1 Answers

This is the problem:

public class ArrayGrid<Sprite> implements Grid<Sprite>

The way you've declared the class, Sprite is the name of a type parameter. You've made this a generic class, and I suspect you didn't mean to. Within that class, Sprite refers to the type parameter, not the type - so you could have an ArrayGrid<String> which implemented Grid<String>... at which point you'd have a string array rather than a sprite array, so it's no wonder that getSymbol() wouldn't work, just as one symptom of the problem.

I suspect you just wanted:

public class ArrayGrid implements Grid<Sprite>

At that point, Sprite really refers to the type. And that means you can avoid the code that wouldn't work around arrays, and instead just write:

this.grid = new Sprite[numRows][numColumns];

Then there's no need to suppress the warnings :)

like image 59
Jon Skeet Avatar answered Dec 21 '22 11:12

Jon Skeet