Monday, May 23, 2011

Inner Classes in Java

There are 4 kind of classes that can be defined in a Java program, roughly can be termed as the inner classes.

--  Inner classes provides an elegant and powerful feature to the Java programming language. 
-- These inner classes are referred by different names in different situations. 

-- They are summarized here:
  1.
Static member classes
  2. Member classes
  3. Local classes
  4. Anonymous classes

-- The term "nested classes" sometimes refers to these inner classes.

Static member classes

  --
This class (or interface) is defined as a static member variable of another class.
Member classes
--  This is sometimes defined as a non-static member of an enclosing class. This type of inner class is analogous to an instance method or field.
Local classes
-- This class is defined within a block of Java code so like a local variable, it is visible only within that block.
Anonymous classes
-- An anonymous class is a  local class having no name; -- Syntactically it combines the syntax required for defining a class and the syntax required to instantiate an object.
 The below is an added little more explanation to the above.


When a class is defined within another class then such a class is called a nested class.
Inner class is a non static class declared inside another class.Non-static inner class keep the reference of outer class and allow to access member variable of outer class. It helps in defining an interface of a class.
We use nested classes because of the following reasons:
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.


Except the inner class, there are two types of supplementary  inner classes :
The inner class which is declared inside the body of a method is known as the local inner classes. The class declared inside the body of a method without naming it is known as anonymous inner classes.
Here we are discussing  anonymous inner classes.
The anonymous inner classes is very useful in some situation. For example consider a situation where you need to create the instance of an object without creating subclass of a class and also performing additional tasks such as method overloading.

Consider the following code :
button.addActionListener(new ActionListener() {
public void actionPerfored(ActionEvent e)
{
// do something.
}
});
As you can see in the above code, i don't need to create an extra class that implements ActionListener . I initiated anonymous inner class(here it is new ActionListener()) without creating a separate class. You can also perform method overloading by implementing anonymous inner classes.

No comments:

Post a Comment