Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

What is Factory Method in Java with Example

A factory method in Java is a static method that creates and returns an object to the class to which it belongs.

For example, getNumberInstance() is a Factory method that belongs to the NumberFormat class. It returns an object to the NumberFormat class.

All factory methods in Java are static methods only.

When to use Factory method in Java?


A single factory method can replace many overloaded constructors in the class by accepting different values from the programmers, while creating the objects.

For example, there are 10 different types of values that we need to pass to an object at the time of creating objects. Then, we will have to create 10 constructors to accept those 10 types of values in the class.

But, we can eliminate it by using factory methods. A single factory method can pass any type of value through a parameter. Generally, we use parameter to pass the different types of values.

Hence, we should create an object by the factory method based on the values passed.

How to use Factory method?


To understand how to use factory method in Java, let’s take an example program to calculate and display area of a circle. In this example program, we will not format the area and display as it is.

// Java program to calculate area of a circle.
package javaProgram;
public class Circle 
{	
public static void main(String[] args) {
 final double pi = (double)22/7; // constant
 double radius = 16.5;
 double area = pi * radius * radius;
 System.out.println("Area of circle: " +area);
  }
}
Output:
       Area of circle: 855.6428571428571

As we know, the digits before the decimal point are integer digits and the digits after the decimal point are fraction digits.

In the output of this example program, there are 13 digits after the decimal point. But, we don’t need these many digits for the most of general purpose.

For example, we don,t need to display over 2 digits after the decimal point to show paisa in the electricity bill. So the question is how to format the output (area) of the circle.

We can achieve it using NumberFormat class of java.text package. This class is useful to format the numerical values.

How to create NumberFormat object using Factory method?


1. We can create NumberFormat class object by using factory method getNumberInstance(). The following code is as:

NumberFormat obj = NumberFormat.getNumberInstance();

2. Now we can use any of the NumberFormat class methods to format the area value.

setMaximumIntegerDigits();
setMinimumIntegerDigits();
setMaximumFractionDigits();
setMinimumFractionDigits();

Now let us write the previous Java program again for calculating and displaying the area of a circle. But, in this program, we will format area of the circle to have maximum 7 integer digits and 2 fraction digits.

// Java program to calculate area of a circle.
package javaProgram;
import java.text.NumberFormat;
public class Circle 
{	
 public static void main(String[] args) {
 final double pi = (double)22/7; // constant
 double radius = 16.5;
 double area = pi * radius * radius;
 System.out.println("Area of circle: " +area);
 
// Create NumberFormat class object using factory method.
   NumberFormat obj = NumberFormat.getNumberInstance();

// Store the format data into obj.
   obj.setMaximumFractionDigits(2);
   obj.setMinimumIntegerDigits(7);
   
// Now apply format to the area value using format() method.
// This format() method returns a string that contains formatted area value. 
   String str = obj.format(area);
 
// Print the formatted area value.
   System.out.println("Formatted area value of the circle: " +str);
  }
}
Output:
      Area of circle: 855.6428571428571
      Formatted area value of the circle: 0,000,855.64

In the above output, you can observe the formatted area value. It has seven integer digits separated properly by commas and two fraction digits.

Also observe that we have used getNumberInstance() method to create an object of NumberFormat class. We have used default format of this method.

There is also another way of using getNumberInstance() method as:

getNumberInstance(Locale constant);

Here, the parameter constant represents the name of a country (locality) as Locale.US, Locale.UK, Locale.CANADA, Locale.JAPAN, etc.

For example, to format a value according to the numerical format of UK, we pass that constant to the NumberFormat object as:

NumberFormat obj = NumberFormat.getNumberInstance(Locale.UK);

If we use constructors in the NumberFormat class in the place of getNumberInstance() method, we will have to write something like this:

NumberFormat(Locale.CANADA);
NumberFormat(Locale.USA);
NumberFormat(Locale.FRANCE);
NumberFormat(Locale.GERMANY);

Creating several constructors in this way is awkwardness in the program. To avoid this boring task, we have used a single factory method getNumberInstance() and passed the required name of the country to it.

Thus, we can use the factory method as an alternative way to create objects rather than the new operator. Therefore, new operator is not only the way to create an object of the class in Java.

In how many ways can we create an object in Java?


There are four ways by which we can create an object in Java. They are as:

1. Using new operator:

Student st = new Student();

Here, we are creating Student class object “st” using new operator.

2. Using factory methods:

NumberFormat obj = NumberFormat.getNumberInstance;

Here, we are creating an object of NumberFormat class using factory method getNumberInstance().

3. Using newInstance() method: To create an object of class using newInstance() method, we will have to follow two steps. They are:

(a) First, store the name of class “Student” as a string into an object. For this purpose, we will use factory method forName() of the class “Class”.

Class c = Class.forName("Student");

You should note that there is also a class with the name “Class” in the java.land package.

(b) Next, make another object to the class whose name is in the object c. For this purpose, we will use the factory method newInstance() method of the class “Class” as:

Student obj = (Student)c.newInstance();

4. By cloning already constructed object, we can create another object. Creating an exact copy (or duplicate copy) of an existing object is called “cloning” in Java.

Student obj1 = new Student();
Student obj2 = (Student)obj1.clone();

Hence, there are several ways to create objects in Java. This is also an important interview question that is asked in the interview from the freshers.

In how many ways you can create an object of a class in Java?


In this tutorial, you learned how to use a factory method in Java with the help of an example program. Hope that you will have understood the basic concepts of factory method.
Thanks for reading!!!

The post What is Factory Method in Java with Example appeared first on Scientech Easy.



This post first appeared on Scientech Easy, please read the originial post: here

Share the post

What is Factory Method in Java with Example

×

Subscribe to Scientech Easy

Get updates delivered right to your inbox!

Thank you for your subscription

×