所以我有一个扩展的类,名为"Furniture"。我将制作每种类型的家具的堆栈,并将堆栈存储在一个数组中。
class Furniture{
private String color;
private String style;
private String height;
private String width;
private String depth;
public Furniture(String c)
{
color = c;
}
public Furniture(String s, String c)
{
color = c;
style = s;
}
public Furniture(String h, String w, String d, String c)
{
height = h;
width = w;
depth = d;
color = c;
}
public Furniture(String s, String h, String c)
{
style = s;
height = h;
color = c;
}
public String getColor()
{
return color;
}
}
该类是扩展
class Bed extends Furniture
{
private String size;
public Bed(String sz,String c){
super(c);
size = sz;
}
}
然后我尝试调用我的getColor()方法
Stack s = new Stack();
s.push(new Bed("queen","red"));
System.out.println(s.peek().getColor());
java:195: error: cannot find symbol
System.out.println(s.peek().getColor());
symbol: method getColor()
location: class Object
我不知道如何解决这个
错误是因为,当peek()栈顶元素时,它返回不包含getColor()法的Object类对象。因此,您只需要使用通用参数Bed创建Stack
你必须更改
Stack s = new Stack();
至
Stack<Bed> s = new Stack<Bed>();
现在,当您查看栈顶元素时,它将返回Bed对象,而不是对象。因此可以解析getColor()。
您的堆栈没有模板,因此它将默认为包含对象。因此,用peek()
返回的对象被视为类object,而不像类Bed。正如您所看到的,Java在Object中找不到getColor()
方法,因为没有。
以下是修复方法:
Stack<Bed> s = new Stack<Bed>();
您应该将Furniture类的对象设置为-
Furniture f=new Furniture("queen","red");
这将执行以下操作:
1.创建一个名为f 的家具类对象
2.将f的大小指定为女王,将其颜色指定为红色。
现在,如果你想打印这个对象的颜色,你应该这样称呼它:
System.out.println(f.getColor());
Stack在java.util.你做的peek()是Stack类的内置方法。所以,你不能像s.peek().getColor()那样调用。如果你在任何一个类中定义了getColor()方法,你需要创建该类的对象,然后你就可以使用该类的方法。您得到Cannot find symbol
是因为在java的Stack类中没有类似getColor()的方法。