"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 > Using interface references

Using interface references

Published on 2024-11-08
Browse:475
  • It is possible to declare a reference variable of an interface type in Java.

  • This variable can reference any object that implements the interface.

  • When a method is called on an object through an interface reference, the version of the method implemented by the object will be executed.

  • This behavior is similar to using a superclass reference to access a subclass object.

Usando referências de interfaces

Usando referências de interfaces

Usando referências de interfaces

Important Points:

  • Reference Variable Declaration:

  • The variable ob is declared as Series ob;, which means that ob can reference any object that implements the Series interface. This allows for flexibility and polymorphism in your code.

  • Reference Storage:

  • In the loop, ob is alternately assigned to twoOb (an instance of ByTwos) and threeOb (an instance of ByThrees). This demonstrates how a single reference variable can be used to manipulate different implementations of the interface.

  • Limited Access:

  • As ob is a Series reference, you can only access the methods defined in the Series interface through it. This means that it is not possible to access methods or variables that are beyond the scope of the interface. For example, if you try to call a method that is not declared in the Series interface, the compiler will generate an error.

  • Advantages:

  • Polymorphism: You can use the same interface reference (ob) to interact with different implementations (such as ByTwos and ByThrees) without having to change the code that uses the reference.

  • Flexibility: Allows you to change the implementation without affecting the code that uses the interface.

Release Statement This article is reproduced at: https://dev.to/devsjavagirls/usando-referencias-de-interfaces-5064?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