Home  >  Article  >  Java  >  Using interface references

Using interface references

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-02 06:17:01782browse
  • 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.

The above is the detailed content of Using interface references. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn