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>由于接口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
}
答案 0 :(得分:7)
所有类都继承自Object。 Object有一个toString。
要使用任何界面,必须由实际的类支持。因此,Java编译器知道在处理接口时它可以使用java.lang.Object中定义的任何方法。
用一种略微不同的方式:
interface I { ... }
有一个“神奇”
interface I extends Object { ... }
因此,您可以在使用I时详细使用Objects方法。但是,您不能在具体类中使用任何未出现在界面中的方法。所以要结合两个例子:
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.
}
}
答案 1 :(得分:3)
Java中的每个类都是Object,因此,它们始终能够运行以下方法:
答案 2 :(得分:2)
因为'toString()'在Object类中,每个非原始数据都是从它派生的。所以每个对象都有这种方法。
答案 3 :(得分:1)
在Java中,您构造的每个类都继承自基类Object。 这意味着默认情况下,您的类将包含许多有用的方法,其中包括toString()。