"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > A more practical example of a standard method

A more practical example of a standard method

Published on 2024-11-08
Browse:691
  • The previous example showed the use of standard methods, but not in a practical scenario.

  • The Series interface was widely used, with many programs dependent on it.

  • It was discovered that several implementations of Series added a method that returns an array with the next n elements of the series.

  • It was decided to improve the Series interface with the getNextArray(int n) method, where n specifies the number of elements to be retrieved.

  • Before standard methods, adding this method would break existing code that did not define it.

  • With standard methods, the new method can be added to the Series interface without causing problems in existing codes.

  • In some cases, standard methods added to an interface report an error if used, when it is not possible to provide an implementation that works in all situations.

  • These default methods define optional code.

  • In certain cases, a default method can be defined to work in any situation.

  • The getNextArray() method is an example, as it can be implemented using the getNext() method already required by the Series interface.

  • It is possible to implement the new version of Series with the standard method getNextArray().

Um exemplo mais prático de um método padrão

  • The standard getNextArray() method is implemented using the getNext() method, already present in the original Series specification.

  • Any class that implements Series can use getNextArray() without having to override the method.

  • Existing code will not be invalidated by adding getNextArray().

  • Classes can provide their own implementation of getNextArray() if necessary.

  • Advantages of the standard method:

  • Allows interfaces to evolve without invalidating existing code.

  • Provides optional functionality without requiring a placeholder implementation.

  • In the case of getNextArray(), if a Series implementation does not need the method, it does not need to provide a placeholder implementation, resulting in cleaner code.

Release Statement This article is reproduced at: https://dev.to/devsjavagirls/um-exemplo-mais-pratico-de-um-metodo-padrao-48c9?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3