2009-09-21 59 views
0
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 
} 

回答

7

所有类自Object继承。对象有一个toString。

要使用任何接口,它必须由实际的类支持。所以Java编译器知道它可以在处理接口时使用java.lang.Object中定义的任何方法。

说得稍微不同的方式:

interface I { ... } 

有一个“神奇”的

interface I extends Object { ... } 

当一细节但是你不能使用任何方法,所以,你可以使用对象的方法没有出现在界面中的具体类。因此,要你把两个例子:

interface Car { 
    void drive(); 
} 

class Convertible implements Car { 
    void drive() {} 
    void openRoof() {} 

    public static void main() { 
    Car porscheBoxster = new Convertible(); 
    porscheBoxster.drive(); // OK - exists in interface 
    porscheBoxster.toString(); // OK - exists in java.lang.Object. 
    porscheBoxster.openRoof(); // Error. All we know is the porscheBoxster is of type Car. 
     // We don't know if it is a Convertible or not. 
    } 
} 
+0

当超类变量用于引用子类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

+0

所有类都从Java中的Object继承。所以Java知道它什么时候遇到一个接口,它将被一个具体的类所支持,所以会有在java.lang.Object中定义的方法 – 2009-09-21 11:07:27

2

因为“的toString()”是在每个非原始数据从派生的类对象。所以每个对象都有这个方法。

3

在Java中的每个类是Object,因此,他们总是能够运行下面的方法:

  • 的clone()
  • 的equals(对象)
  • 的finalize()
  • 的getClass ()
  • 的hashCode()
  • 通知()
  • notifyAll的()
  • 的toString()
  • 等待()
  • 等待(长)
  • 等待(长,INT)
1

在Java中,每次构建类,从基类对象继承。 这意味着你的类默认会有很多有用的方法,其中包括toString()。