简体   繁体   English

Java中的接口和抽象类

[英]Interfaces and Abstract Classes in Java

Does interfaces and abstract classes in Java extend base Object class? Java中的接口和抽象类是否扩展了基本Object类? Logical answer which I can think of is no, but if interface does not extend Object class, then can please someone explain me the below code: 我能想到的逻辑答案是“否”,但是如果接口不扩展Object类,那么请有人向我解释以下代码:

interface A { 

@Override 
public int hashCode(); 

@Override 
public String toString(); 

} 

In above case, A interface is the new interface declared. 在上述情况下, A接口是声明的新接口。 Yet, no class is implementing it. 但是,目前还没有班级实施它。 Then how come the methods from Object class visible in the interface? 那么,如何在接口中看到Object类中的方法呢?

If it doesn't extend Object class, then why I can't declare following method in the interface: 如果它没有扩展Object类,那为什么我不能在接口中声明以下方法:

public Class getClass();

When I tried to declare this method in the interface, it says that it can't override this method, inherited from Object class, as it is declared as final method in Object class. 当我尝试在接口中声明此方法时,它说它无法覆盖从Object类继承的此方法,因为它在Object类中声明为final方法。

Interface could only extend some other interface and no - there is no some root interface. 接口只能扩展其他接口,而不能扩展-没有任何根接口。 Abstract class, as any other class in Java, has Object as its ancestor - while it may not be a direct parent. 与Java中的其他任何类一样,抽象类也将Object作为其祖先-尽管它可能不是直接父代。

Methods, marked as final , could not be overriden in successor classes. 标记为final的方法不能在后继类中覆盖。 As your class has Object as its ancestor - this rule also applies here. 由于您的类将Object作为其祖先-此规则在这里也适用。

The reason this is can be found in JLS $9.2 可以在JLS $ 9.2中找到原因。

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 a method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface. 如果接口没有直接的超接口,则该接口隐式声明带有签名s的公共抽象成员方法m,返回类型r,并引发与每个带有签名s的公共实例方法m,返回类型r和throws子句t对应的子句t在Object中声明,除非接口显式声明了具有相同签名,相同返回类型和兼容throws子句的方法。

It is a compile-time error if the interface explicitly declares such a method m in the case where m is declared to be final in Object. 如果在Object中将m声明为final的情况下,接口显式声明了这样的方法m,则是编译时错误。

And as seen in Object#getClass : Object#getClass

public final Class<?> getClass()

Interfaces do not inherit from Object , but they do mimick the methods available by implicitly adding them. 接口继承Object ,但他们做的模拟天生可通过隐含加入它们的方法。 Likewise here, a final method in that base interface can't be overridden in your self-defined interface. 同样,在此基础接口中的final方法不能在自定义接口中被覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM