使用接口引用访问java Object类方法 [英] Accessing the java Object class methods using an interface reference

查看:214
本文介绍了使用接口引用访问java Object类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑以下示例。

public interface SimpleInterface {
    public void simpleMethod();
}

public class SimpleClass implements SimpleInterface{

 public static void main(String[] args) {
     SimpleInterface iRef = new SimpleClass();
     SimpleClass cRef = new SimpleClass();
     iRef.simpleMethod(); // Allowed. Calling methods defined in interface via interface reference.
     cRef.specificMethod(); // Allowed. Calling class specific method via class reference.
     iRef.specificMethod(); // Not allowed. Calling class specific method via interface reference.
     iRef.notify(); // Allowed????

 }

 public void specificMethod(){}

 @Override
 public void simpleMethod() {}

}

我想,在使用接口引用的Java中,我们只能访问在这个界面。但是,似乎允许通过任何接口引用访问类Object的方法。我的具体类SimpleClass继承了Object类所具有的所有方法,并且类Object确实没有实现任何接口(假设Object使用notify,wait等方法实现某些接口)。我的问题是,为什么允许通过接口引用访问类Object的方法,考虑到我的具体类中的其他方法是不允许的?

I thought, in Java using interface reference we may access only methods that are defined in this interface. But, it seems that it is allowed to access method of class Object via any interface reference. My concrete class "SimpleClass" inherits all the methods that class Object has and definitely the class Object doesn't implement any interface (one would assume that Object implements some interface with methods like notify, wait and etc.). My question is, why it is allowed to access methods of the class Object via interface reference, taking into consideration that other methods in my concrete class are not allowed?

推荐答案


为什么允许它通过接口引用访问类对象的方法

您可以使用接口引用调用 Object 类方法,尽管接口不会从<$ c扩展$ c> Object class,因为Java中的每个根接口都有对应于 Object class的每个方法的隐式方法声明。

You can invoke the Object class methods using an interface reference although an interface doesn't extend from Object class, because every root interface in Java has implicit declaration of method corresponding to each method of Object class.


JLS§ 9.2 - 界面成员

界面的成员是:


  • 如果接口没有直接的超接口,隐式声明一个公共抽象成员方法m,其签名为
    s,返回类型为r,throws子句t对应于每个带有签名s的公共
    实例方法m,返回类型为r ,并在对象中声明的throws子句t
    ,除非具有相同签名的方法,相同的
    返回类型和兼容的throws子句由
    接口显式声明。 / li>
  • 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.

这篇关于使用接口引用访问java Object类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆