我有一个代码:
interface My {
//this is left empty
}
class Test implements My {
public static void main(String[] args){
My m=new Test();
String str=m.toString(); //how reference variable m calls toString() in Test even it is not in My?
System.out.println(str);
str=m.show(); //Error:
System.out.println(str);
}
public String toString(){
return "Hello";
}
public String show(){
return "World";
}
}
str=m.show()
的错误是cannot find symbol str=m.show()
和location: variable m of type My
。
我的问题是m.toString()
如何报告任何错误,m.show()
报告此类错误。
答案 0 :(得分:4)
toString()
在Object
中定义。接口的任何具体实现也将扩展Object
,因此您可以调用Object
中声明的任何方法。
答案 1 :(得分:1)
toString类在Object类中定义,所有对象都包含Test
。所以Java中对象的每个实例都有这个方法。您可以在派生类Test
中覆盖它,并且将调用此方法而不是基础方法。
就其他错误消息关注show
方法而言,m
变量的类型是My
接口,并且此接口内没有定义此类方法。
答案 2 :(得分:0)
toString方法是Object类的方法,因此所有Java对象都有toString。您的对象m使用My类型声明,而接口My没有名为“show”的方法