What is the main difference between an inner class and a static nested class in Java?

Technology CommunityCategory: JavaWhat is the main difference between an inner class and a static nested class in Java?
VietMX Staff asked 3 years ago

In short nonstatic nested class can access instance of the container class, while static can’t.

nested class could be nonstatic or static and in each case is a class defined within another class. A nested class should exist only to serve is enclosing class, if a nested class is useful by other classes (not only the enclosing), should be declared as a top level class.

  • Nonstatic Nested (Inner) class : is implicitly associated with the enclosing instance of the containing class, this means that it is possible to invoke methods and access variables of the enclosing instance. One common use of a nonstatic nested class is to define an Adapter class.
  • Static Nested Class : can’t access enclosing class instance and invoke methods on it, so should be used when the nested class doesn’t require access to an instance of the enclosing class . A common use of static nested class is to implement a components of the outer object.