Introduction
In this article we are going to describe the concept of a Nested class. The Java programming language allows you to define a class within another class. Such a class is called a nested class. Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.
Reasons for using nested classes
There are several compelling reasons for using nested classes, among them:
- It is a way of logically grouping classes that are only used in one place.
- It increases encapsulation.
- Nested classes can lead to more readable and maintainable code.
A normal class is a direct member of a package, a top-level class. Inner classes, which became available with Java 1.1, come in four flavors:
- Static member classes
- Member classes
- Local classes
- Anonymous classes
Static Member classes
In a nested scenario a static member class is treated as a static member of a class in which that class is nested like other static methods and static variables. A static member class has access to all static methods of the parent, or top-level, class.
Syntax
public class Temp
{
// class functionality
private static class StaticNested
{
// you cna put his functionality
}
}
Member classes
In member class is also defined as a member of a class. Unlike the static variety, the member class is specific to an instance and has access to any and all methods and members, even the parent's this
reference.
Example
public class Top
{
int x=10
class Member
{
public metho1()
{
system.out.println("this is member class");
}
}
public static void main(String arg[])
{
Member m= new Member();
m.method();
System.out.println("this from top class");
}
}
Local class
In a local class the class can be declared inside any function or any block. And this is not visible from anywhere only, instances of this class cannot be created and used within the scope in which it is declared. This can be useful if you need to hide an ancillary object, which should not be accessible or used anywhere.
public java.util.Enumeration enumerate()
{
class Enumerator implements java.util.Enumeration
{
Linkable current;
public Enumerator()
{
current = head;
}
public boolean hasMoreElements()
{
return (current != null);
}
public Object nextElement()
{
if (current == null) throw new java.util.NoSuchElementException();
Object value = current;
current = current.getNext();
return value;
}
}
return new Enumerator();
}
Anonymous class
An Anonymous class is nothing. It is a local class but without a name. In other words an anonymous class is a local class without a name. An anonymous class is defined and instantiated in a single succinct expression using the new operator.
Syntax
submittButton.addKeyListener
(
new KeyListener()
{
public void actionPerformed ( KeyEvent event )
{
Object o = event.getSource();
if ( o == submittButton )
{
System.out.println("i am sucess");
}
}
}
);
Resources