What is the factory design pattern in Java?

In object-oriented programming, the factory design pattern is one of the most famous design patterns. In this pattern, objects are created without specifying their exact class.

This is achieved by specifying in an interface and implementing by child classes, or, by implementing in a base class and overriding by child classes.


Example

In the class diagram below, the GenerateBill class can not generate a bill directly. Instead, the Factory class generates the correct type of bill using computeBill().

svg viewer

Implementation

main.java
Factory.java
Billing.java
Commercial.java
Domestic.java
Institutional.java
public class main {
public static void main(String[] arguments) {
Factory bill = new Factory();
//get an object of Domestic Billing and call its getBill() method.
Billing bill_1 = bill.computeBill("Domestic");
bill_1.getBill();
}
}
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved