开发者

By implementing an interface, does a class become a "Type" of that inteface?

I thought when a class implements an interface, it is saying that it "Can do" whats defined in the interface.I am also under impression that "Is a" or "Type of" notation is for class hierarchy, meaning a class inheriting from superclass. Is my understanding correct开发者_JS百科?


From the title Question I would say no.

There have been answers saying yes and showed this by using instanceof, however when reading the Java language specification it states.

two reference types are the same run-time type if: They are both class or both interface types, are defined by the same class loader, and have the same binary name

And a class implementing an interface won't receive the binary name of the interface.


Yes. This is evident from use of the instanceof operator:

    interface I { }

    class A implements I { }

    ...

    static boolean isAnI(Object obj) {
       return (obj instanceof I);
    }

Here, calling isAnI(new A()) will return true.

EDIT: after understanding the question better, I think this comes down to the formal definition of IS-A in Java. Wikipedia article on the general OO definition here. From this inheritance-hierarchy based perspective, I would change my answer to no, agreeing with Farmor's answer.


I'm not entirely sure I understand your question. But, the interface does say what the class "Can do" but then you can also cast an object of that interface and run the methods of the interface. Polymorphism at work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜