cast an object to an interface in java?

后端 未结 8 1715
半阙折子戏
半阙折子戏 2021-02-01 23:36

if we cast an object to an interface, won\'t this object be able to call its own methods? in the following example, myObj will only be able to call MyInterface meth

8条回答
  •  情歌与酒
    2021-02-02 00:20

    In the code you showed you never perform any casts.

    A typical use of an interface is to define some methods which will be available, without caring about the concrete implementation.

    A nice example of this are the listeners in the standard JDK. For example the PropertyChangeListener. This is an interface which defines a method which can be called when 'a property is changed'. A typical use of this interface is to attach it to a class which has properties, and this class will warn those listeners when one of its properties has changed.

    The class does not care what those listeners will do. It only relies on the fact this propertyChange method will be present, and calls that method.

    The class can only call this method on the listener, since it only knows about the method defined in the interface. If those listeners have other methods, they can call those methods themself, but that is only because they know they are more then the interface.

提交回复
热议问题