gpt4 book ai didi

java - 多态性和对象类

转载 作者:行者123 更新时间:2023-11-30 06:16:49 25 4
gpt4 key购买 nike

我们知道每个类都是从 Object 扩展的,这意味着我们可以使用 Object 的所有方法在任何类(class)。我的问题如下:

   interface B{

}

public class A implements B{
public static void main(String[] args){

B i = new A();
i.display();//we can't do this : because the interface B doesn't define such a method

System.out.println(i.toString());// we can do this although the interface doesn't extend from Object

}
public void display(){

}

}

所以我认为问题很清楚,为什么我可以调用 toString 方法,尽管接口(interface) B 不能从 Object 扩展?

最佳答案

这在 JLS §9.2. Interface Members 中有详细说明:

  • If an interface has no direct superinterfaces, then the interface implicitly declares a public abstract member method m with signature s, return type r, and throws clause t corresponding to each public instance method m with signature s, return type r, and throws clause t declared in Object, unless an abstract method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface.

这确保可以通过任何接口(interface)调用 Object 方法。

关于java - 多态性和对象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26571824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com