Reference Variables and Interfaces

Contact Us or call 1-877-932-8228
Reference Variables and Interfaces

Reference Variables and Interfaces

An interface is like a class where the internal structure and some of the behavior is hidden.

  • Interfaces are listed like classes in the API documentation.
  • They compile to a .class file, and get loaded by the same process that loads true classes.

Since a class that implements an interface is a class in all other respects, you can create a reference variable for that class, as usual.

You can also create a reference variable whose type is the interface name.

  • Only the methods defined in the interface are visible through a variable whose type is the interface.
    • For a Printable variable containing a Stock instance, the sell method is not visible, since it is not declared in Printable.
  • Any constants defined by the interface can be accessed without a prefix from code within the class, since implementing the interface makes them part of this class.

To access an interface-implementing class with an interface class reference:

[modifiers] InterfaceName variableName;

Example:

  • Both Person and Stock implement Printable.
  • Therefore, we can create a reference variable to a Printable, and assign either a Person or a Stock object to it.
  • We can then call the printAll() method from the Printable reference variable, since the compiler knows that method will exist, no matter which type of object is actually stored in the variable.
Person p = new Person();
Stock s = new Stock();
Printable pr;
pr = p;

or

pr = s;

or

pr = new Person();

Calling an Interface Method

If you have a variable that is declared as a reference to the interface type, you can use it to call an interface method.

  • Note that you cannot call any of the additional methods that are not defined by the interface.

Code Sample:

Java-Interfaces/Demos/PrintableTest.java
public class PrintableTest {
  public static void main(String[] args) {
    Person p = new Person();
    Stock s = new Stock();

    p.printAll();
    s.printAll();

    Printable pr;
    pr = p;
    pr.printAll();
    pr = s;
    pr.printAll();
  }
}

Once pr has been assigned a Printable instance, we can call pr.printAll();

  • We cannot directly call the sell() method when pr refers to a Stock, since the compiler would not associate it with a variable whose type was Printable.

Note: to compile this, use *.java; since the name of the file containing Stock and Person is PrintableThings.java, the compiler won't be able to find those classes, since it would be looking for Person.java and Stock.java.

Note: you can test the type of object actually contained in an interface reference, and typecast it back to that type.

  • for instance, to use the sell() method for a Stock:
if (pr instanceof Stock) ((Stock) pr).sell();
Next