Types of classes in Java

Types of classes in Java

Previous Home Next

 

There are six different, sometimes overlapping, classifications of classes.
Top level classes,Nested classes,Static classes,Inner classes,Anonymous classes,Local classes



   1. Top level classes: not nested, but possibly sharing a *.java file.
   2. Nested classes: class within the class (either static or inner).
   3. Static classes: no associated outer class instance.
   4. Inner classes: with an associated outer class instance.
   5. Anonymous classes: unnamed inner class defined in the middle of a method
                                                                           .
   6. Local classes: named inner class defined in the middle of a method. 
 A top level class is the one that all Java developers will be familiar with as without it one can not develop software at all. 
package example;

public class Demo {
public static void main(String[] args) {

}
}

Static member classes sometimes called static inner classes although they aren't strictly inner are the first and most common type of nested class. A nested class is defined inside the body of an enclosing class and should only be present to assist the enclosing class.


 package example;

public class Demo
{
} {
private static class Nested {

}
}
Non Static inner class
 There is only one small difference between the declaration of a static and non-static member class
 but in terms of functionality the difference is huge.

Anonymous classes

The most common use of anonymous classes is with GUI development where they are attached as
 listeners to the various widgets. Probably the second most common use of anonymous classes is as filters and comparators.

A local class is declared inside a method body .
It is only accessible to the method it is declared in which makes local classes less generally useful than non-static inner classes.

package example;

public class Demo
{

public Demo() {
class Local {
public Local() {
System.out.println( "In local class...");
}
}
new Local();
}





 
Local class

package
example;

public class Demo
{

public Demo() {
class Local {
public Local() {
System.out.println( "In local class...");
}
}
new Local();
}





Previous Home Next