Nested classes are classes defined inside the body of an outer class. A nested class is not always an inner class, as only the latter exist in the outer object.
In Java there are fundamentally four types of nested classes and here are their characteristics:
Type Static Locale Anonymous May extend/ Can be final Interface/class support be extended or abstract --------------------------------------------------------------------------------------------------- Static nested yes no no ext./be ext. yes outer: both; inner: both class Regular inner no no no ext./be ext. yes outer: class;inner: both class Local inner class no yes no ext./be ext. yes outer: method; inner: class Anonymous inner no yes yes ext. no outer: method; inner: class class Type static Can only see final explicit Can be private Only static members vars in outer scope constructor or public members --------------------------------------------------------------------------------------------- Static nested yes no yes yes yes class Regular inner yes no yes yes no class Local inner class no yes yes no no Anonymous inner no yes no no no class
A "static nested class" is exactly like a normal class, except the fact of being accessed through an outer class.
public class Outer { static class Inner { // Some code here } // Some code here } public class Test { public static void main(String[] args) { Outer.Inner inner = new Outer.Inner(); } }
A "regular inner class" is a normal non-static class, inside an outer class.
public class Outer { private class Inner { // Some code here } public void doSomething() { Inner inner = this.new Inner(); // Some code here } }
Note that member variables of the inner class are only accessible by creating an instance of it.
A "Local inner class" is defined in the body of a method. It can only be accessed from the body of code in which it's defined.
public class Outer { public Box doSomething() { class Inner extends Box { // Some code here } return new Inner(); } }
Note that you can only pass final variables to a local inner class.
An "anonymous class" is exactly like a "local inner class", but doen't have a name. It's often used to override a method on-the-fly.
public class Outer { public Box doSomething() { return new Box() { // Some code here } } }
Note that it can't be extended or have constructors.
Only the static member class is nested but not inner, as it cannot access the outer object.
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.