interface I
{
void show();
}
class A implements I
{
void show()
{
System.out.println("class A");
}
public static void main(String s[])
{
I i=new A();
i.show();
i.toString();
}
}
Q> As接口I不包含抽象方法toString()但仍然編譯下面的代碼。怎麼樣?覆蓋使用接口的方法
當超類變量用於引用子類obj時,編譯器首先搜索超類中的類似方法,如果未找到會給出錯誤。 這裏接口不包含方法toString()。
EX =>
class A
{
void show()
{
System.out.println("show");
}
}
class B
{
void show()
{
System.out.println("show B");
}
void display()
{
System.out.println("display B");
}
public static void main(String s[])
{
A a=new B();
a.show(); //will execute
a.display(); //give error
}
當超類變量用於引用子類obj時,編譯器首先搜索超類中的類似方法,如果未找到會給出錯誤。 這裏接口不包含方法toString()。 ex => A級 { void show() { System.out。println(「show A」); } } B類 { 空隙顯示() { 的System.out.println( 「顯示B」); } void display() { System.out.println(「display B」); } public static void main(String s []) {a} = new B(); a.show(); //將執行 a.display(); //給出錯誤 } – yash 2009-09-21 11:02:42
所有類都從Java中的Object繼承。所以Java知道它什麼時候遇到一個接口,它將被一個具體的類所支持,所以會有在java.lang.Object中定義的方法 – 2009-09-21 11:07:27