cast an object to an interface in java?

后端 未结 8 1711
半阙折子戏
半阙折子戏 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:13

    A simple analogy:

    Consider a Chef(Interface). And there are Chinese chef(classes) and American chef(classes). Now, there is a Hotel looking out to recruit a chef based on some eligibility criteria such as

    • can cook Non-vegeterian
    • can cook vegeterian
    • have experience of 5 years

    Here, the eligibility is the context within which the Chef type person is evaluated(Types functionality). Now, there may be cases where Chinese chef can also cook sea food , Italian dishes etc. so could be the case with American counterpart. All these may seem irrelevant to Hotel manager as he is only concerned with required criteria.

    Chefs work in a hotel is analogous to Chef type object utilised in code. The obvious work would be to cook vegeterian and non-vegeterian food(criteria or interface methods). That does not mean that the Hotel cannot utilize the Chinese chef's sea food making skills.

    It's just a matter of specifying what skills(functionality) the Hotel is looking for.

    Hope you get the idea.

提交回复
热议问题