• 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:


  1. package instanceofjavaTutorial;
  2.  
  3. public class Outer{ 
  4.  
  5.   static class inner{
  6.  
  7. public void print(){
  8.  
  9. System.out.println("static inner class method called");
  10.  
  11. }
  12.  
  13. }
  14.  
  15. public static void main(String args[]){
  16.  
  17. Outer.inner in= new Outer.innner();
  18.  
  19. in.print();
  20.  
  21. }

Output:

  1. static inner class method called



Static inner class accessing outer class static variable:

  1. package instanceofjavaTutorial;
  2.  
  3. public class Outer{ 
  4.  static int a=10;
  5.   static class inner{
  6.  
  7. public void print(){
  8.  
  9. System.out.println(a);
  10.  
  11. }
  12.  
  13. }
  14.  
  15. public static void main(String args[]){
  16.  
  17. Outer.inner in= new Outer.innner();
  18.  
  19. in.print();
  20.  
  21. }

Output:

  1. 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.
Non-static nested class(inner class)
  1. Member inner class
  2. Anonymous inner class
  3. 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

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu