Home>

Can classes in java be static?The answer is yes.In java we can have static instance variables, static methods, and static blocks. Classes can also be static.

Java allows us to define static classes in a class.For example, the nested class. Enclosed nested classes are called outer classes.In java, we cannot decorate top level classes with static. Only inner classes can be static.

What is the difference between a static inner class and a non-static inner class?Here are the main differences between the two.

(1) Internal static classes do not need to have references to external classes.But non-static inner classes need to hold references to outer classes.

(2) Non-static inner classes can access static and non-static members of outer classes.Static classes cannot access non-static members of external classes.He can only access static members of external classes.

(3) A non-static inner class cannot be created without an outer class entity,A non-static inner class can access data and methods of the outer class,Because he is in the outer class.

Based on the discussion above,We can use these features to make programming easier and more efficient.

/* The following program shows how to create a static inner class and a non-static inner class in Java * /
class outerclass {
  private static string msg="geeksforgeeks";
  //static inner class
  public static class nestedstaticclass {
    //Static inner class can only access static members of outer class
    public void printmessage () {
     //try changing msg to non-static,This will cause compilation errors
     system.out.println ("message from nested static class:" + msg);
    }
  }
  //non-static inner class
  public class innerclass {
    //Both static and non-static methods can be accessed in non-static inner classes
    public void display () {
     system.out.println ("message from non-static nested class:" + msg);
    }
  }
}
class main
{
  //How to create instances of static inner classes and non-static inner classes
  public static void main (string args []) {
    //create an instance of a static inner class
    outerclass.nestedstaticclass printer=new outerclass.nestedstaticclass ();
    //Create a non-static method of a static inner class
    printer.printmessage ();
    //To create a non-static inner class,We need an instance of the outer class
    outerclass outer=new outerclass ();
    outerclass.innerclass inner=outer.new innerclass ();
    //call a non-static method of a non-static inner class
    inner.display ();
    //We can also combine the above steps,Create an inner class instance in one step
    outerclass.innerclass innerobject=new outerclass (). new innerclass ();
    //Similarly we can now call inner class methods
    innerobject.display ();
  }
}
  • Previous Parsing Java's InputStream class and using it to read ppt files
  • Next C # example of three ways to pass parameters to multiple threads