Factory methods:-
Factory method
A factory method is one whose return type is similar to name of the class where it presents
getLocalGraphicsEnvironment ();
RULES for factory method:
1. The return type of the factory method must be similar to name of the class where it
presents.
2. Every factory method must be static (so that we can call with respect to name of the class).
3. Every factory method must be public.
Factory methods are used for creating an object without using new operator.
Every predefined abstract class contains at least one factory method for creating an object of abstract class
- Factory methods are static methods only.But their intension is to create an object depending on the user choice.
- A factory method is a method that returns an object to the class,to which it belongs.
- A single factory method replaces several constructors in the class by accepting different options from the user,while creating the object.
ex:- w.a.p to calculate the area of a circle.
class Circle
{
public static void main(String args[])
{
final double PI=(double)22/7;
double r=15.5;
double area=PI*r*r;
System.out.println("Area of circle :"+area);
}
}
o/p : Area of circle :755.0714285714286
In the above program the decimal part contains 13 digits, to display the 2 or user specific decimals we have to use the NumberFormat class.
ex:- getNumberInstance() is a Factory method.Because it belongs to NumberFormat class and returns an object to NumberFormat class
some NumberFormat methods are:
- setMaximumIntegerDigits();
- setMinimumIntegerDigits();
- setMaximumFractionDigits();
- setMinimumFractionDigits();
Apply the format to the required statement using format() method.This method returns a string that contains formatted area value.
No comments:
Post a Comment