not implementing all of the methods of interface. is it possible?

前端 未结 10 1919
挽巷
挽巷 2020-11-28 03:33

Is there any way to NOT implement all of the methods of an interface in an inheriting class?

相关标签:
10条回答
  • 2020-11-28 04:14

    I asked myself the same question, and then learned about Adapters. It solved my problem, maybe it can solve yours. This explains it very well : https://blogs.oracle.com/CoreJavaTechTips/entry/listeners_vs_adapters

    0 讨论(0)
  • 2020-11-28 04:15

    We can use Adapter classes ,which reduces complexcity by not making mandatory to implement all the methods present in the interface

    Adapter class is a simple java class that implements an interface with only EMPTY implementation . Instead of implementing interface if we extends Adapter class ,we provide implementation only for require method

    ex--- instead of implementing Servlet(I) if we extends GenericServlet(AC) then we provide implementation for Service()method we are not require to provide implementation for remaining meyhod..

    Generic class Acts as ADAPTER class for Servlet(I).

    0 讨论(0)
  • 2020-11-28 04:19

    The point of an interface is to guarantee that an object will outwardly behave as the interface specifies that it will

    If you don't implement all methods of your interface, than you destroy the entire purpose of an interface.

    0 讨论(0)
  • 2020-11-28 04:22

    Define that class as an abstract class. However, you must implement those unimplemented methods when you want to create an instance of it (either by using a subclass or an anonymous class).

    0 讨论(0)
  • 2020-11-28 04:25

    The only way around this is to declare your class as abstract and leave it to a subclass to implement the missing methods. But ultimately, someone in the chain has to implement it to meet the interface contract. If you truly do not need a particular method, you can implement it and then either return or throw some variety of NotImplementedException, whichever is more appropriate in your case.

    The Interface could also specify some methods as 'default' and provide the corresponding method implementation within the Interface definition (https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html). These 'default' methods need not be mentioned while implementing the Interface.

    0 讨论(0)
  • 2020-11-28 04:28

    It is possible and it is easy. I coded an example.

    All you have to do is inherit from a class that does implement the method. If you don't mind a class that is not instantiable, then you can also define an abstract class.

    0 讨论(0)
提交回复
热议问题