The simplest way to instantiate a Java object is shown in Listing 3.1.
Listing 3.1 public static void main(String args[]) { Main cls = new Main(); }
In Listing 3.1, the class Main is instantiated using the new keyword. Once the object has been instantiated, the developer can manipulate the object however he pleases. Might this pose a problem? Well, yes; objects are allocated using a hard reference, in that the consumer references directly the class to manipulate. In the previous chapter, we learned that the Commons Bridge is a good practice to follow when you're writing code, but we didn't show how to instantiate the Commons Bridge classes. Listing 3.2 illustrates a very simple example of the Commons Bridge.
Listing 3.2 interface InterfaceToBeShared { void availability(); } class SomeFunctionality implements InterfaceToBeShared { public void availability() { System.out.println( "Yes we have bananas today"); } }
In Listing 3.2, the interface InterfaceToBeShared is an interface that will be used globally. The class SomeFunctionality implements the interface InterfaceToBeShared. A consumer of the classes can therefore use the interface InterfaceToBeShared if he requires the functionality of the class SomeFunctionality. Listing 3.3 shows the simplest way to instantiate the classes defined in Listing 3.2.
Listing 3.3 InterfaceToBeShared intrf = new SomeFunctionality(); intrf.availability();
The instantiation in Listing 3.3 is simple and logical, but it shows a huge problem. To be able to use the interface InterfaceToBeShared, the class SomeFunctionality has to be instantiated. The advantage of abstracting the interface from the implementation is lost in that single instantiation. The instantiation of the interface requires a reference to the class SomeFunctionality. The rest of this chapter shows how to get around the problem of a direct class reference.