如何toString
使用interface的引用变量调用方法Test
,而没有toString
方法呢?
interface Test
{
void show();
String toHi();
}
class Demo implements Test
{
public void show(){
System.out.println("Show");
}
public String toString(){
return "Hello";
}
public String toHi(){
return "Hi";
}
public static void main(String[] args)
{
Test t=new Demo();
String s=t.toString();
System.out.println(s);
}
}
Run Code Online (Sandbox Code Playgroud)
Kum*_*tra 12
在该Java文档说...
When an interface has no direct SuperInterface, it will create abstract public method for all those public methods present in the Object class
.
这就是您能够toString()
在接口引用上调用该方法的原因
Joh*_*eek 11
Object
有一个toString()
方法,所以一切(基本类型除外)都有一个toString()
方法.Java会将任何东西,甚至是空接口都视为具有所有方法Object
,因为它始终如此.
归档时间: |
|
查看次数: |
9879 次 |
最近记录: |