This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
Factory methods are not part of the exam. To add to that the Factory pattern by itself is split into the Abstract Factory pattern and the Factory method pattern. The details however are not needed for the SCJP
Originally posted by Deepak Bala: Factory methods are not part of the exam. To add to that the Factory pattern by itself is split into the Abstract Factory pattern and the Factory method pattern. The details however are not needed for the SCJP
But there was a question in Master Exam, asking, "Which of the following classes are instantiated by factory methods?" That's why I asked the definition. Well... Thanks for the information
@Brij garg your code has a mistake, it will not compile as you are accessing a non-static field from a static method.
@arijit, you can understand this as follows
If you want that no one can create an instance of your class, and you provide a method that provides instances of that class, that method is called factory method. So basically a factory method returns an instance of its own class.
To do this you will have to create all the constructors of the class private and have to create a static public method, that returns an instance of that class. The method might return new instance every time or might return the same instance all the time as in the example by brij.
There are many reasons for this. Your class might be incomplete in itself like the Calendar class, which has a getInstance method which returns an instance of GregorianCalendar class usually. Other reason might be that you want that only one instance of the class be created on one JVM as shown in the code by brij...