Inner Classes: Classes within another classes are known as Nested or Inner Classes.Difference Between Inner Classes and Normal Classes:
Normal class: does not have a class within another class and is a top level class and a member of package.
Inner Classes: does have a class within another class and is a member of enclosing/outer class.
Additional Information:
- Inner Classes were introduced in Java 1.1.
- They may be defined as public, protected, private, or with package access.
- The outer class can freely instantiate inner class objects within its code; they are automatically associated with the outer class instance that created them.
- Code in some other class can instantiate an inner class object associated with a specific instance of the outer class if the inner class definition is public (and its enclosing/outer class is public as well)
- If the inner class is static, then it can be instantiated without an outer class instance, otherwise, the inner class object must be attached to an instance of the outer class.
- Inner class code has free access to all elements of the outer class object that contains it, by name (no matter what the access level of the elements is).
- Outer class code has free access to all elements in any of its inner classes, no matter what their access term.
- No inner class objects are automatically instantiated with an outer class object.Outer class code may instantiate any number of inner class objects - none, one, or many.
- An inner class compiles to its own class file, separate from that of the outer class (the name of the file will be OuterClassName$InnerClassName.class, although within your code the name of the class will be OuterClassName.InnerClassName); you cannot use the dollar sign version of the name in your code.
- An inner class occupies its own memory block, separate from the outer class memory block.
- An inner class may extend one class, which might be unrelated to the class the outer class extends.
- An inner class can implement one of more interfaces, and, if treated as an instance of one of its interfaces, external code may have no knowledge that the object actually comes from an inner class.
- Inner classes are best used in the event handling mechanism and to implement the helper classes. The advantage of using inner class for event handling mechanism is that the use of if/else to select the component to be handled can be avoided. If inner classes are used each component gets its own event handler and each event handler implicitly knows the component it is working
Button btn1 = new Button("Submit");
Btn.addActionListener(new ActionListener()
{/br>
Public void actionPerformed(ActionEvent ae)
{ submitClicked(); }
} );
Inner Class Syntax:
[modifiers] class OuterClassName {
code
[modifiers] class InnerClassName [extends BaseClassToInner] [SomeInterface[, MoreInterfaces, ...]] {
fields and methods
}
Inner Class Sample:
public class OuterExample {
private int num1;
OuterExample(int num1, int num2) {
this.num1 = num1;
new MyInner(num2).privateDisplay();
}// end of constructor
public class InnerExample {
private int num2;
InnerExample(int num2) {
this.num2 = num2;
} // end of constructor
private void privateDisplay() {
System.out.println("privateDisplay num1 = " + num1 + " and num2 = " + num2);
} // end of privateDisplay()
public void publicDisplay() {
System.out.println("publicDisplay num1 = " + num1 + " and num2 = " + num2);
} // end of publicDisplay()
} // end of InnerClass
} // end of OuterClass
OuterExample has one property, x; the inner class MyInner has one property, y.
The OuterExample constructor accepts two parameters; the first is used to populate x.
It creates one InnerExample object, whose y property is populated with the second parameter.
Note that the inner class has free access to the private outer class x element.
The outer class has free access to the private inner class privateDisplay() method.
The connection between the two classes is handled automatically.
The OuterExample constructor accepts two parameters; the first is used to populate x.
It creates one InnerExample object, whose y property is populated with the second parameter.
Note that the inner class has free access to the private outer class x element.
The outer class has free access to the private inner class privateDisplay() method.
The connection between the two classes is handled automatically.
Class Files Generation for Inner Classes
As we mentioned earlier each class can have more than one inner classes. Once the main class is compiled which has several inner classes, the compiler generates separate class files for each of the inner class. Have a look at below example.// Main class
public class Main {
// Inner class Test1
class Test1 {
}
// Inner class Test2
class Test2 {
}
public static void main(String [] args) {
// Anonymous inner class 1
new Object() {
};
// Anonymous inner class 2
new Object() {
};
System.out.println("Hello World");
}
}
Here we have a Main class which has four inner classes. Test1, Test2, Anonymous inner class 1 and Anonymous inner class 2. Once we compile this class using javac command, the compiler will generates following class files.
Main.class
Main$Test1.class
Main$Test2.class
Main$1.class
Main$2.class
Advantages:
- Increases level of encapsulation : They can be hidden from the other classes in the same package and still have the access to all the members (private also) of the enclosing class. So the outer class members which are going to be used by the inner class can be made private and the inner class members can be hidden from the classes in the same package. This increases the level of encapsulation.
- Inner classes allow us to further organize our package structure through the use of namespaces. Instead of dumping everything in a flat package, classes can be further nested within classes. Explicitly, without inner classes, we were limited to the following hierarchy structure:
package1
class 1
class 2
...
class n
...
package n
With inner classes we can do the following:
package 1
class 1
class 2
class 1
class 2
...
class n
...
class n
...
package n
Used carefully, inner classes can provide a structural hierarchy that more naturally fits your classes.
3. The callback : Provide a specialized form of callback, with which a class may pass very limited access to some of its internal components. Note that:
The collections classes provide an iterator, a class that implements the Iterator interface to loop through the elements in the collection using hasNext and next methods.Given that the internal structure of the collection may be complex, implementing the iterator as an inner class enables it to navigate the structure, while not exposing any other aspects of the collection to the outside world.
4. Having the ability to define nested classes will help grouping the related functionality together, imagine the case in which a certain class is being used only once from within another class, then there is no obvious need to add a clutter to the enclosing package by defining a top-level-class that will merely be used by only one another class. Thus, having that functionality contained within a a nested class increase readability and reduce clutter.
package1
class 1
class 2
...
class n
...
package n
With inner classes we can do the following:
package 1
class 1
class 2
class 1
class 2
...
class n
...
class n
...
package n
Used carefully, inner classes can provide a structural hierarchy that more naturally fits your classes.
3. The callback : Provide a specialized form of callback, with which a class may pass very limited access to some of its internal components. Note that:
The collections classes provide an iterator, a class that implements the Iterator interface to loop through the elements in the collection using hasNext and next methods.Given that the internal structure of the collection may be complex, implementing the iterator as an inner class enables it to navigate the structure, while not exposing any other aspects of the collection to the outside world.
The collections classes provide an iterator, a class that implements the Iterator interface to loop through the elements in the collection using hasNext and next methods.Given that the internal structure of the collection may be complex, implementing the iterator as an inner class enables it to navigate the structure, while not exposing any other aspects of the collection to the outside world.
4. Having the ability to define nested classes will help grouping the related functionality together, imagine the case in which a certain class is being used only once from within another class, then there is no obvious need to add a clutter to the enclosing package by defining a top-level-class that will merely be used by only one another class. Thus, having that functionality contained within a a nested class increase readability and reduce clutter.
Disadvantages :
- From a maintenance point of view, inexperienced Java developers may find the inner class difficult to understand.
- The use of inner classes will also increase the total number of classes in your code. JVM may have to perform some routine tasks for these extra classes created which may result slower performance if the application is using more number of inner classes.
- Inner classes get limited support of ide/tools as compared to the top level classes, so working with the inner classes is sometimes annoying for the developer.
Types Of Inner Classes: There are four types of inner classes:
- Static inner classes:
- Static members of the outer class are visible to the static inner class, what ever their access level be.
- Non-static members of the outer class are not available, because there is not instance of the outer class.
- An inner class may not have static members unless the inner class is itself marked as static.
- Sometimes static nested class are not reffered to as inner class at all, as they don’t require outer classes instance.
- A static inner class is just like any other inner class, but it dose not have the reference to its outer class object that generated it
Static Inner Class Sample:
public class OuterClass{
static int i =10; private int private_member_variable = 100;
public static class StaticInnerClass { static int j =1000;
public void printPrivateVariables() { OuterClass outerClass = new OuterClass(); System.out.println(outerClass.private_member_variable);
System.out.println(outerClass.i);
System.out.println(j);
} }
public static void main(String args[]) { StaticInnerClass staticInnerClass = new StaticInnerClass(); staticInnerClass.printPrivateVariables(); }}
Output:
100
10
1000
- Non Static Inner classes
- Member Classes:
- Classes declared outside a function (hence a "member") and not declared "static".
- The member class can be declared as public, private, protected, final and abstract. .
- Cannot include any static members within the inner class.
- These are the most widely used type of nested classes, the following code excerpt shows how to define a an inner class within a normal top-level-class, how easily the private members of the enclosing class can be accessed by the nested class and how to obtain an instance of the inner class from within the enclosing class:
Member Class Sample:
public class OuterClass
{
static int i =10;
private int private_member_variable = 100;
public class MemberInnerClass
{
//static int j =1000; //does not include static member in the inner class
public void printPrivateVariables()
{
//OuterClass outerClass = new OuterClass();
System.out.println(private_member_variable);
System.out.println(i); //call outer class static members
}
}
public static void main(String args[])
{
//StaticInnerClass staticInnerClass = new StaticInnerClass(); // cannot directly call the class
OuterClass outerClass = new OuterClass(); // called using outer class instance
OuterClass.MemberInnerClass memberInnerClass = outerClass.new MemberInnerClass();
memberInnerClass.printPrivateVariables();
}
}
Call From outside Class:
public class TestClass
{
public static void main(String args[])
{
OuterClass outerClass = new OuterClass();
OuterClass.MemberInnerClass memberInnerClass = outerClass.new MemberInnerClass();
memberInnerClass.printPrivateVariables();
}
}
2. Local Classes:
- Local classes are never declared with an access specifier (that is, public or private). Their scope is always restricted to the block in which they are declared.
- Local classes have a great advantage: they are completely hidden from the outside world.
- They can not only access the instance variables but local variables of the method (in which they are defined) as well, but the local variable has to be declared final.
- Do not need to instantiate the local class can instantiate the outer class and call the method of the outer class.
Local Class Syntax:
<access-specifier> class <OuterClassName> {
code...
<access-specifier> <return-type> <MethodName>(<arguments>){
class <LocalInnerClassName>{
code...
}
code...
}
code...
}
Local Class Sample:
public class LocalInnerClass {
int i = 9;
static int j = 10;
public void method1() {
final int k = 6;
class MethodLocal {
void doMethodLocal() {
System.out.println(k + i);
System.out.println(i);
System.out.println(j);
}//end of inner method
} // end off local class
MethodLocal methodLocal = new MethodLocal(); // should be declared after the local class is defined
methodLocal.doMethodLocal();
} // end of outer class method
public static void main(String args[])
{
//StaticInnerClass staticInnerClass = new StaticInnerClass(); // cannot directly call the classLocalInnerClass localInnerClass = new LocalInnerClass(); // called using outer class instance
//LocalInnerClass.MethodLocal memberInnerClass = outerClass.new MethodLocal(); // do not need to instantiate the local class call using the instance of the outerclass
localInnerClass.method1();
} // end of main method3. Anonymous Classes:
When using local inner classes, you can often go a step further. If you want to make only a single object of this class, you don’t even need to give the class a name.
Such a class is called an anonymous inner class. Usually the inner class extend some interface or extend other class.
Anonymous Classes Syntax
new SuperType(construction parameters) {
inner class methods and data
}
- Here, SuperType can be an interface, such as ActionListener; then, the inner class implements that interface. Or SuperType can be a class; then, the inner class extends that class.
- An anonymous inner class cannot have constructors because the name of a constructor must be the same as the name of a class, and the class has no name. Instead, the construction parameters are given to the superclass constructor. In particular, whenever an inner class implements an interface, it cannot have any construction parameters. Nevertheless, you must supply a set of parentheses as in
- It is recommended to refrain from using them as many programmers find too many anonymous classes hard to read.
- Anonymous class cannot define any static fields, methods, or classes, except for static final constants.
- Also, like local classes, anonymous classes cannot be public, private, protected, or static
Anonymous Classes Sample
class hasAnonymous{
superClass anon = new superClass(){
void doSomething() {
System.out.println(“Doing something in the Anonymous class”);
}
};

No comments:
Post a Comment