Builder patterns using inner static classes in Java

Firstly what are inner classes? A class inside a class?? Exactly! Now what is the purpose of these inner classes. If we want to create an object only associated with a parent object i.e, we don’t want child object without parent object, how do we achieve that. Even before that, ask this question, “Where even such kind of scenario exists?”

Maybe not the best example, but think it in this way; A relation between planet and a man. If we don’t want to imagine or create a man without a planet to live on. Here goes the structure…

class Planet {​
class Man {​}​
}​

We have to create an instance of Planet before creating an instance of Man.

Planet p = new Planet();
Planet.Man man = p.new Man();

Now suppose we want single star/sun associated with all the planets created using the Planet class. In that case, we define a static class, Sun, inside the Planet class. This will make sure that there is only one star, whose attributes if changed in future will reflect for all the planets.

class Planet {​​
static class Sun {​
private static temparature​ = 10340;
private static void setTemparature(int newTemparature) {​
temparature = newTemparature;
}​
static int getTemparature(){​
return temparature;
}​
}
class Man {​​}​​
}​​

Now we can change the static variables associated with Sun either through instance or ClassName. Either ways it will reflect in all other instances.

Planet.Sun.setTemparature(11000);
sun.getTemparature(); // returns 11000

Note: In the above example, we have used static methods which will enable us to access these method without creating object through class reference. Instance methods inside static class can be reference only though objects.

Hence inner static classes are helpful in achieving builder patterns, which comes under creative design pattern.

Hope you found this article helpful. Have a nice day!