Tutorial
Menus

Java Beginners - Java For Beginners

Java Inner Class

Rating: 3.7/5 (3 votes cast)

Level   : Beginners
Author : Arunkumar S
Download Source : Outter.java

Java Inner Class - What are Nested/Inner classes.

Up until the introduction of Jdk 1.1, the java language only supported top-level classes. Top level classes are classes that are defined as members of a package. But with Jdk 1.1, sun introduced the concept of nested/inner classes in java. Nested/inner classes are classes within classes. Inner/Nested classes makes it much easier for developer to connect object together, since classes can be defined closer to the objects. First of all before you go any further, you must know that this feature of java is only limited to the compiler. In other words to compile java code that contains nested/inner classes, you will need Jdk 1.1 or later but the compiled code can be executed on any jvm. You've probably used inner classes already in java without noticing it. A typical example of the usage of an inner class is when creating an adapter class to listen to events in a GUI. Nested/inner classes gives a developer lots of power, but when they are not properly use or understood, they can be very confusing. Here is the main difference between Nested and Inner classes


Nested class


    A nested class has the same behavior as any static member of a class. You can have access to it without initializing the parent class, and they can access the parent class static methods and variables also. Nested classes are always define with the keyword static (and we will see later that this is what differentiate them from the inner classes). An access tag (i.e. : public, protected or private) can be defined, but by default a nested class takes the default package access. Sun considers nested classes to be top-level classes (I find this at times to be confusing). Here is an example of how to define a nested class MyInner in the class enclosing class MyOuter.
 
class MyOuter {

public static class MyInner {
//...
public void function1() {}
//more function (static and more)
}
}

Notice that when you compile this code, you will have two .class file as the output :

MyOuter.class : being the enclosing class.

MyOuter$MyInner.class : being the inner class.     Since class MyInner is a static member of MyOuter, it can be access from anywhere in your code using MyOuter.MyInner (The same way that you access classes in packages, you can even use the import statement with nested classes : import MyOuter.MyInner).
 

Example :

    Here is the code to call the constructor of class MyInner anywhere in your code :

 public MyInner myclass = MyOuter.MyInner();

    However, if the class MyOuter was define in the package my.package you will write :

 
MyInner myclass = my.package.MyOuter.MyInner();

    As you can see you do not have to create an instance of class MyOuter to use class MyInner. Class MyOuter serves a package for class MyInner. Personally I would recommend not using Nested classes (unless you really think that no classes outside the scope your object would ever want to use the nested classes), most of the time, it is much easier and cleaner to define the class in a separate .java file instead.
 


Inner Class


   

Inner class differ very much from nested class because it does not have a static tag, as a matter of fact you can never write an inner class with the static tag (when you add the static tag it automatically becomes a nested class). Unlike a nested class, every instance of an inner class requires an instance of the enclosing class, and an enclosing class can have multiple instance of the inner class. Without going into too much details, here are the three types of inner class:


Member inner classes


    This type of inner class is defined as members of the enclosing class, they are defined on the same level as function and variables of a class, and have the same behavior and properties.
 
Example :
class MyOuter
{
private float variable = 0;
public void donothing() { //do your stuff }
private class MyInner
{
public void innerfunction() {//do your stuff }
public void function()
{
//Do your stuff
//Here is how you call a function with the same name
//from the enclosing class
MyOutter.this.donothing();
}
}
}

The inner class MyInner class is a Member inner class. Notice in the example above, I had a name conflict with the enclosing class MyOuter when trying to call the function donothing(), that is why I added the line MyOuter.this.donothing(). This forces the compiler to get take the current instance of the enclosing class function instead.


Local inner classes


This type of inner class is defined inside a bloc of code. However, like any object they can live beyond the scope of the bloc of code inside witch they are defined, this depends on what you do with them.
 
Example :
Interface MyInterface
{
public String getInfo();
}
class MyOuter
{
MyInterface current_object;
public void setInterface(String info)
{
class MyInner implement MyInterface
{
private String info;
public MyInner(String inf) {info=inf;}
public string getInfo() {return info;}
}
current_object = new MyInner(info);
}
}
In the example above, the class MyInner is a local inner class.

Anonymous inner classes

This is a very special type of inner class. An anonymous inner class usually does not have a name. You probably used anonymous inner classes before. They are often used in GUI development to implement listeners. Here is an example of the most frequent use of anonymous inner class in java.
 
Example :

class Outer extends java.awt.Frame
{
public Outer()
{
java.awt.Button button = new java.awt.Button("Click on me");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("You clicked");
}
});
}
}
In the code above the class ActionListener is an anonymous class.

Advantages of using Nested/Inner class

Inner class be very powerful;l development tools when you know how to use them. Here are a just a few advantages that nested/inner classes can give you.

Blocs of codes.


One of the main reasons sun introduced Nested/Inner classes in java is to give developers the ability to implement blocs of codes, that can be used to realize special functions inside a given object (pointers to methods). Using inner classes you can integrate blocs of code inside your object to perform special task pretty much like you have method pointers in C.


Integrate object in objects


By giving the developers the ability to integrate blocs of code in objects via inner class, developer now have the ability to integrate objects in objects, this is a very big advantage since your code can now have a more object oriented design. You can create special objects as part of another object. In a way your code can become much easier to read, and also your code is more object oriented. Now it is possible to separate the logic in your objects in inner objects. Example if you have a class Engine, and you define an interface EnginePower in the same package. You can create a inner object that implement the interface EnginePower inside the class Engine for a specific type of engine (i.e. JetEngine). This is a pretty efficient method of coding since you know that the inner class EnginePower is tightly linked to the enclosing class Engine and the user would only want to access the EnginePower interface


Callbacks.


Inner class are also very useful when you want to implement callbacks. A very good example of the advantage of using an inner class for callbacks is when implementing GUI event listeners (see example above). If you try to implement the callback procedure mention in the example for anonymous inner class without inner class, then you will have to implement the ActionLlistener interface in a class and this would force you to use a bunch of if and else if to figure out on which object the event occurred. Using inner classes allows you to efficiently have a separate bloc of code to do handle the actionPerformed function for every graphic component object.
 

1 | 

Discussion about this tutorial

  Start a new Discussion | Read All Discussion
Subject RepliesLast Post
Javaorigin.com contact@javaorigin.com