Creating an Object

The simplest way to instantiate a Java object is shown in Listing 3.1.

Listing 3.1
start example
 public static void main(String args[]) { Main cls = new Main();  } 
end example

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
start example
 interface InterfaceToBeShared { void availability(); } class SomeFunctionality implements InterfaceToBeShared { public void availability() { System.out.println( "Yes we have bananas today"); } } 
end example

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
start example
 InterfaceToBeShared intrf = new SomeFunctionality(); intrf.availability(); 
end example

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.

Applied Software Engineering Using Apache Jakarta Commons
Applied Software Engineering Using Apache Jakarta Commons (Charles River Media Computer Engineering)
ISBN: 1584502460
EAN: 2147483647
Year: 2002
Pages: 109 © 2008-2017.
If you may any questions please contact us: