我正在尝试使用 length()
方法打印出String
的长度,但我不断收到标题中提到的错误。我是Java的新手,我认为这种方法是内置到IDE(Eclipse)中的。
import class JumbleHelper {
String word;
public JumbleHelper(String jumbleWord)
{
word = jumbleWord;
}
public static void main(String[] args)
{
JumbleHelper str1 = new JumbleHelper("maybe");
System.out.println(str1.length());
}
}
你还没有在 jumblehelper 中实现一个名为 'length' 的函数。仅仅因为它中唯一的值是一个字符串并不意味着你可以使用它的所有函数。这不是继承的运作方式。
但是,str1.word.length() 可以工作。
或者,您可以在 jumblehelper 中添加一个名为 length 的函数,如下所示:
public int length(){ return word.length() };
str1 的类型是 "JumbleHelper" 而不是字符串。
- 如果你真的想用JumbleHelper来封装一个字符串(在这种情况下,有一个静态的主方法会非常奇怪),在JumbleHelper中添加一个长度函数。
- 否则,直接使用 String 对象的 Length 函数。
如果类JumbleHelper
有String
,那么这并不意味着它有它的方法。 Composition
与inheritance
不同。事实上,你不能继承String
因为它是final
你可能的意思是
JumbleHelper str1 = new JumbleHelper("maybe");
System.out.println(str1.word.length());
因为你的类JumbleHelper不提供这些函数,所以你必须像这样添加它,或者像上面描述的那样在类对象上调用单词
public JumbleHelper(String jumbleWord)
{
word = jumbleWord;
}
public int length (){
return this.word.length();
}
我只添加了这个解决了它:import java.lang.String;