Qbert Qbert - 5 months ago 8
Java Question

Accessing ItemType methods within Stack

I'm having trouble accessing a method in my ItemType class, from a Stack of ItemTypes.

My ItemType class is very simple

public class SteveItemType{

private String name;


public SteveItemType(String name){
this.name = name;
}
public String getName(){
return this.name;
}

}


My toString method from my Stack class:

public String toString(){
return stack[top].getName(); }


This is where my error is hiding. I believe whats being stored inside my stack is not an object type (which is disabling me from accessing my getName method)

My Bounded Stack constructors are:

public ArrayStack(){
stack = (SteveItemType[]) new Object[default_cap]; }

public ArrayStack(int n){
stack = (SteveItemType[]) new Object[n]; }


Finally in my application, this is how I am pushing my ItemType & creating my stack:

ArrayStack stack = new ArrayStack<SteveItemType>(n);

stack.push(new SteveItemType("Steve"));


My error is

> ArrayStack.java:59: error: cannot find symbol
> return stack[top].getName();


Please if anyone could explain why/where my logic/thinking is wrong I very appreciate it, my apologies for all the moving parts I try to make as precise as possible.

(I am unable to access my getName method)

Answer

Could you please following snippet of code as applicable in ArrayStack.java:

public class ArrayStack<T extends SteveItemType> {

private SteveItemType[] stack;  
private int top;    
private int default_cap=5;

public ArrayStack(){
      stack = new SteveItemType[default_cap]; 
  }

public ArrayStack(int size) {
    this.stack = new SteveItemType[size];
  }

public String toString(){
      return stack[top].getName();
  }

public void push(T t){
    // push an object
  } 
  // more methods follows
}

and tell me whether your problem is gone or not?