I am attempting to use a stack to put objects in a stack. I have a Pixel class that has a simple getX function that returns a variable defined in the constructor. When I use the stack.peek().getX(); it says that it cannot find the symbol for .getX();
Stack stack = new Stack();
Pixel first = new Pixel(colorX,colorY);
stack.push(first);
int x = stack.peek().getX();
Am I using the peek function wrong? Or do I have my Pixel class setup incorrectly?
public class Pixel {
private int x, y , count = 0;
Pixel(int x_in, int y_in)
{
x = x_in;
y = y_in;
}
public int getX(){return x;}
public int getY(){return y;}
It is because you are using a raw Stack
, instead of Stack<Pixel>
that you get this error. A raw stack is essentially equivalent to Stack<Object>
, so when you call peek()
it returns Object
and not Pixel
.
Even though the runtime type may be Pixel
, method resolution happens at compile time and Object
has no getX()
method.