In this tutorial, you will learn about nested static class with the help of examples.
A static class i.e. created inside a class is called static nested class in java. It cannot access non-static data members and methods. It can be accessed by outer class name.
1.It can access static data members of outer class including private.
2.Static nested class cannot access non-static (instance) data member or method.We use the keyword static to make our nested class static.In Java, only Nested classess are allowed to be static.
For Example :
class City
{
//members of Cirty class
static class Bhopal
{
//static and non-static members of Bhopal class
}
}
To access the static nested class, we don’t need objects of the outer class.
Example :
class City
{
// inner class
class Bhopal
{
public void displayInfo()
{
System.out.println("Welcome to Bhopal");
}
}
// static class
static class Pune
{
public void displayInfo()
{
System.out.println("Welcomme to Pune");
}
}
}
class Main
{
public static void main(String[] args)
{
// object creation of the outer class
City city = new City();
// object creation of the non-static class
City.Bhopal bhopal = city.new Bhopal();
bhopal.displayInfo();
// object creation of the static nested class
City.Pune pune = new City.Pune();
pune.displayInfo();
}
}
Output
Welcome to Bhopal
Welcome to Pune