- Yes we can create a class as static. But class should be inner class or nested class.
- We know how to create static methods, static variables and static blocks.
- As Java Supports defining a class within a class we can create a static inner class inside a class.
- This inner static class inside a class can access static members of outer class even its private.
Java Program to create static inner class:
- package instanceofjavaTutorial;
- public class Outer{
- static class inner{
- public void print(){
- System.out.println("static inner class method called");
- }
- }
- public static void main(String args[]){
- Outer.inner in= new Outer.innner();
- in.print();
- }
- }
Output:
- static inner class method called
Static inner class accessing outer class static variable:
- package instanceofjavaTutorial;
- public class Outer{
- static int a=10;
- static class inner{
- public void print(){
- System.out.println(a);
- }
- }
- public static void main(String args[]){
- Outer.inner in= new Outer.innner();
- in.print();
- }
- }
Output:
- 10
- In java there are two types of nested classes one is static and another one is non static nested classes.
- We saw static classes in java lets see what will be there in non static nested classes.
- Member inner class
- Anonymous inner class
- Local inner class
- A class is defined within a class and outside of methods of that class known as member inner class.
- Anonymous inner class is a inner class which does not have a name and whose instance is created at the time creating class itself.
- A class which is defined inside a method of another class known as local inner class
Click here for more information about inner classes
No comments