HelpEzee

Tuesday, August 14, 2012

What are mutable objects and immutable objects?

An Immutable object is a kind of object whose state cannot be modified after it is created. This is as opposed to a mutable object, which can be modified after it is created.

In Java, objects are referred by references. If an object is known to be immutable, the object reference can be shared. For example, Boolean, Byte, Character, Double, Float, Integer, Long, Short, and String are immutable classes in Java, but the class StringBuffer is a mutable object in addition to the immutable String.

class Program
{
     public static void main(String[] args)
    {
      String str = "HELLO";
      System.out.println(str);
      str.toLowerCase();
      System.out.println(str);
   }
 }
The output result is
 HELLO
 HELLO

From the above example, the toLower() method does not impact on the original content in str.
 What happens is that a new String object “hello” is constructed. The 
toLower() method returns the new constructed String object’s reference. 
Let’s modify the above code:

class Program {
  public static void main(String[] args) {
    String str = "HELLO";
    System.out.println(str);
    String str1 = str.toLowerCase();
    System.out.println(str1);
  }
}
The output result is
HELLO
hello
 
The str1 references a new String object that contains “hello”. The String object’s method never affects the data the String object contains, excluding the constructor.

In Effective Java, Joshua Bloch makes this recommendation: “Classes should be immutable unless there’s a very good reason to make them mutable….If a class cannot be made immutable, you should still limit its mutability as much as possible.”

What are the guidelines to implement immutable object? Please visit Immutable Object.

Difference between String, StringBuffer and StringBuilder in Java

String is most commonly used class in Java programming. Java also provides two other classes StringBuffer and StringBuilder. We need to carefully choose between these three depending on the requirement. Thus it is important to understand difference among them.

Points of Difference

1. String class objects are immutable objects means that they can’t be altered. It always creates a new object when we try to change them. However StringBuffer and StringBuilder classes are mutable and one can change the contents of it.
Example: To concatenate String s1=”ABC” and String s2=”DEF” using “+” operator we need another string. String s3 = s1+s2 and s3 will have the value of “ABCDEF”.But using StringBuffer or StringBuilder the same scenario in this case can be s1.append(“DEF”) and s1 becomes “ABCDEF”. They are provided by append() and insert() methods.

2. When we use the String object to concatenate two strings, the first string is combined to the other string by creating a new copy in the memory as a string object because they are immutable objects. This process is a little long.StringBuffer / StringBuilder are mutable, doesn’t create new objects every time. Thus usage of StringBuilder / StringBuffer is more efficient in case large amounts of string manipulations have to be performed.

3. The String class overrides the default equals() method, but StringBuffer and StringBuilder do not override the default equals() method in Object class. The equals() method for class Object implements the most discriminating possible equivalence relation on objects that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

Example:

public class Program {
  public static void main(String [] args) {
    String s1 = new String("Hello World");
    String s2 = new String("Hello World");
    System.out.println("s1.equals(s2):" + s1.equals(s2));
    StringBuffer sb1 = new StringBuffer("Hello World");
    StringBuffer sb2 = new StringBuffer("Hello World");
    System.out.println("sb1.equals(sb2):" + sb1.equals(sb2));
    StringBuilder sd1 = new StringBuilder("Hello World");
    StringBuilder sd2 = new StringBuilder("Hello World");
    System.out.println("sd1.equals(sd2):" + sd1.equals(sd2));
  }
}
 
The output is
s1.equals(s2):true
sb1.equals(sb2):false
sd1.equals(sd2):false

4. StringBuffer and StringBuilder have the same methods with one difference and that’s of synchronization. StringBuffer is synchronized (which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized (which implies it isn’t thread safe).

5. It is recommended to use StringBuilder over StringBuffer whenever possible because it is faster than StringBuffer. However if thread safety is necessary the best option is StringBuffer objects.

6. StringBuilder class is relatively new and was introduced in Java 1.5 whereas String and StringBuffer are old classes. StringBuffer and String class was introduced in JDK 1.0

Criteria to choose among String, StringBuffer and StringBuilder

1. If your text is not going to change use a string Class because a String object is immutable.

2. If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized.

3. If your text can change and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous.

Monday, August 6, 2012

Enumeration (Enum) in Java

Enumeration (Enum) in Java was introduced in JDK 1.5 and it is one of my favorite features of J2SE 5. Java Enum as type is more suitable on certain cases for example representing state of Order as NEW, PARTIAL FILL, FILL or CLOSED. Enumeration(enum) was not originally available in Java though it was available in other language like C and C++ but eventually Java realized and introduced Enum on JDK 5 (Tiger) by keyword enum. In this Java enum tutorial we will see different enum example in java and learn using enum in java. Focus of this java enum tutorial will be on different features provided by Enum in Java and how to use them. If you have used Enumeration before in C or C++ than you will not be uncomfortable with Java enum but in my opinion Enum in Java is more rich and versatile than in any other language.

How to represent enumerable value without Java enum

java enum example, enum in java tutorialSince Enum in Java is only available from Java 1.5 its worth to discuss how we used to represent enumerable values in Java prior JDK 1.5 and without it. I use public static final constant to replicate enum like behavior. Let’s see an enum example in java to understand the concept better. In this example we will use US Currency Coin as enumerable which has values like PENNY (1) NICKLE (5), DIME (10), and QUARTER (25).

class CurrencyDenom {
            public static final int PENNY = 1;
            public static final int NICKLE = 5;
            public static final int DIME = 10;
            public static final int QUARTER = 25;

      }

class Currency {
   int currency; //CurrencyDenom.PENNY,CurrencyDenom.NICKLE,
                 // CurrencyDenom.DIME,CurrencyDenom.QUARTER
}

 Though this can server our purpose it has some serious limitations:

 1) No Type-Safety: First of all it’s not type-safe; you can assign any valid int value to currency e.g. 99 though there is no coin to represent that value.

 2) No Meaningful Printing: printing value of any of these constant will print its numeric value instead of meaningful name of coin e.g. when you print NICKLE it will print "5" instead of "NICKLE"

3) No namespace: to access the currencyDenom constat we need to prefix classname e.g. CurrencyDenom.PENNY instead of just using PENNY though this    can also be achieved by using static import in JDK 1.5

Java Enum is answer of all this limitation. Enum in Java is type-safe, provides meaningful string names and has there own namespace. Now let's see same example using Enum in Java:

public enum Currency {PENNY, NICKLE, DIME, QUARTER};
 
Here Currency is our enum and PENNY, NICKLE, DIME, QUARTER are enum constants. Notice curly braces around enum constants because enums are type like class and interface in Java. Also we have followed similar naming convention for enum like class and interface (first letter in Caps) and since Enum constants are implicitly static final we have used all caps to specify them like Constants in Java.

What is Enum in Java

Now back to primary questions “What is enum in java” simple answer enum is a keyword in java and on more detail term java enum is type like class and interface and can be used to define a set of enum constants. Enum constants are implicitly static and final and you can not change there value once created. Enum in Java provides type-safety and can be used inside switch statment like int variables. Since enum is a keyword you can not use as variable name and since its only introduced in JDK 1.5 all your previous code which has enum as variable name will not work and needs to be re-factored.

Benefits of Enums in Java:

1) Enum is type-safe you can not assign anything else other than predefined enum constant to an enum variable.

2) Enum has its own name-space.

3) Best feature of Enum is you can use Enum in Java inside Switch statement like int or char primitive data type.we will also see example of using java enum in switch statement in this java enum tutorial.

4) Adding new constants on Enum in Java is easy and you can add new constants without breaking existing code.

Important points about Enum in Java

1) Enums in Java are type-safe and has there own name-space. It means your enum will have a type for example "Currency" in below example and you can not assign any value other than specified in Enum Constants.
 
public enum Currency {PENNY, NICKLE, DIME, QUARTER};
Currency coin = Currency.PENNY;
coin = 1; //compilation error  

2) Enums in Java are reference type like class or interface and you can define constructor, methods and variables inside java enum whichmakes it more powerful than Enum in C and C++ as shwon in next example of java enum type.

3) You can specify values of enum constants at the creation time as shown in below example:
public enum Currency {PENNY(1), NICKLE(5), DIME(10), QUARTER(25)};
But for this to work you need to define a member varialbe and a constructor because PENNY (1) is actually calling a constructor which accepts int value , see below example.
  
public enum Currency {
        PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
        private int value;

        private Currency(int value) {
                this.value = value;
        }
};  
Constructor of enum in java must be private any other access modifier will result in compilation error. Now to get the value associated with each coin you can define a public getValue () method inside java enum like any normal java class. Also semi colon in the first line is optional.

4) Enum constants are implicitly static and final and can not be changed once created. For example below code of java enum will result in compilation error:

Currency.PENNY = Currency.DIME;
The final field EnumExamples.Currency.PENNY cannot be re assigned.

5) Enum in java can be used as an argument on switch statment and with "case:" like int or char primitive type. This feature of java enum makes them very useful for switch operations. Let’s see an example of how to use java enum inside switch statement: 
   Currency usCoin = Currency.DIME;
    switch (usCoin) {
            case PENNY:
                    System.out.println("Penny coin");
                    break;
            case NICKLE:
                    System.out.println("Nickle coin");
                    break;
            case DIME:
                    System.out.println("Dime coin");
                    break;
            case QUARTER:
                    System.out.println("Quarter coin");
    }
  


6) Since constants defined inside enum in java are final you can safely compare them using "==" equality operator as shwon in following example of   java enum:
Currency usCoin = Currency.DIME;
    if(usCoin == Currency.DIME){
       System.out.println("enum in java can be"+
               "compared using ==");
    }

7) Java compiler automatically generates static values () method for every enum in java. Values() method returns array of enum constants in the same order they have listed in enum and you can use values() to iterator over values of enums in java as shown in below example:

for(Currency coin: Currency.values()){
        System.out.println("coin: " + coin);
    }
And it will print:
coin: PENNY
coin: NICKLE
coin: DIME
coin: QUARTER
               
Notice the order its exactly same with defined order in enums.

8) In Java Enum can override methods also. Let’s see an example of overriding toString () method inside enum in java to provide meaningful description for enums constants.
public enum Currency {
  ........
      
  @Override
  public String toString() {
       switch (this) {
         case PENNY:
              System.out.println("Penny: " + value);
              break;
         case NICKLE:
              System.out.println("Nickle: " + value);
              break;
         case DIME:
              System.out.println("Dime: " + value);
              break;
         case QUARTER:
              System.out.println("Quarter: " + value);
        }
  return super.toString();
 }
};        
And here is how it looks like when displayed:
Currency usCoin = Currency.DIME;
System.out.println(usCoin);

output:
Dime: 10
 
9) Two new collection classes EnumMap and EnumSet are added into collection package to support java enums. These classes are high performance implementation of Map and Set interface in Java and we should use this whenever there is any opportunity.

10) You can not create instance of enums by using new operator in java because constructor of Enum in Java can only be private and Enums constants can only be created inside Enums itself.

11) Instance of enums in java is created when any enums constants are first called or referenced in code.

12) Enum in Java can implement the interface and override any method like normal class It’s also worth noting that enum in java implicitly implement both Serializable and Comparable interface. Let's see and example of how to implement interface using java enum:
public enum Currency implements Runnable{
  PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
  private int value;
  ............
        
  @Override
  public void run() {
  System.out.println("Enum in Java implement interfaces");
                
   }
}

13) You can define abstract methods inside enum in Java and can also provide different implementation for different instances of enum in java.  Let’s see an example of using abstract method inside enum in java

public enum Currency implements Runnable{
          PENNY(1) {
                  @Override
                  public String color() {
                          return "copper";
                  }
          }, NICKLE(5) {
                  @Override
                  public String color() {
                          return "bronze";
                  }
          }, DIME(10) {
                  @Override
                  public String color() {
                          return "silver";
                  }
          }, QUARTER(25) {
                  @Override
                  public String color() {
                          return "silver";
                  }
          };
          private int value;

          public abstract String color();
        
          private Currency(int value) {
                  this.value = value;
          }
          ..............
  }      
In this example since every coin will have different color we made the color () method abstract and let each instance of enum to define   there own color. You can get color of any coin by just calling color () method as shown in below example of java enum:

System.out.println("Color: " + Currency.DIME.color());

 Enum java valueof example
One of my reader pointed out that I have not mention about valueOf method of enum in Java, which is used to convert String to enum in java.  Here is what he has suggested, thanks @ Anonymous
“You could also include valueOf() method of enum in java which is added by compiler in any enum along with values() method. Enum valueOf() is a static method which takes a string argument and can be used to convert a String into enum. One think though you would like to keep in mind is that valueOf(String) method of enum will throw "Exception in thread "main" java.lang.IllegalArgumentException: No enum const class" if you supply any string other than enum values.

Another of my reader suggested about ordenal() and name() utility method of java enum Ordinal method of java enum returns position of a enum constant as they declared in enum while name()of enum returns the exact string which is used to create that particular enum constant.”

That’s all on Java enum , Plesae share if you have any nice tips on enum in Java  and let us know how you are using java enum in your work.

Saturday, August 4, 2012

Difference between Enumeration and Iterator


Both Enumerator and Iterator provides a way to traverse/navigate/iterate through a collection.

Enumerator is there in java since early age i.e JDK1.0 and Iterator was introduced in JDK1.2 with collections.

Iterator is more secure and safe as compared to enumeration because if some other thread wants to modifies the same collection concurrently, Iterator throws CocurrentModificationException.

Iterator interface is a duplicate copy of Enumerator interface while providing extra feature to remove elements.
 

Below code explains about traversal of ArrayList collection using both : 

Enumeration : 

List myList = new ArrayList();
myList.add("Hello");
myList.add("World");
myList.add("New");
myList.add("Example");
Enumeration enums = Collections.enumeration(myList);
while (enums.hasMoreElements())
System.out.println("" + enums.nextElement());
Iterator : 
List myList = new ArrayList();
myList.add("Hello");
myList.add("World");
myList.add("New");
myList.add("Example");
Iterator iterator = myList.iterator();
while (iterator.hasNext())
System.out.println("" + iterator.next());
Note:
  • Iterators allows to safe removal of elements from the collection during the iteration by using remove method of Iterator (not by collection's remove method) . Enumeration does not have remove method. 
  • Iterators are fail-fast . i.e. when one thread changes the collection by add / remove operations , while another thread is traversing it through an Iterator using hasNext() or next() method, the iterator fails quickly by throwing ConcurrentModificationException . The fail-fast behavior of iterators can be used only to detect bugs. The Enumerations returned by the methods of classes like Hashtable, Vector are not fail-fast that is achieved by synchronizing the block of code inside the nextElement() method that locks the current Vector object which costs lots of time. 
  • Enumeration is twice as fast as Iterator and uses very less memory. Enumeration is very basic and fits to basic needs. But Iterator is much safer as compared to Enumeration, b’ coz it always denies other threads to modify the collection object which is being iterated by it. Whenever a second thread tries for that Iterator will throw a ConcurrentModificationException. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly.
  • Before using iterator.remove(), the Iterator should point to any of its elements.
    The remove() removes the element which the Iterator correctly pointing to
    Otherwise it will throw IllegalStateException  
 

Friday, July 27, 2012

Inner Classes in java


Inner classes, also called Nested Classes, are nothing but classes that are defined within other classes. The nesting is a relationship between classes, not objects.
Inner classes have clearly two benefits, name control & access control. In Java, this benefit is not as important because Java packages give the name control.
Inner classes may be defined with following access modifiers: public, protected, private, or with default package access.
The syntax for inner class is as follows:
[modifiers] class OuterClassName {
    code...
    [modifiers] class InnerClassName {
        code....
    } }


Inner Class:

Following properties can be noted about Inner classes:
ü  The outer class (the class containing the inner class) can instantiate as many number of inner class objects as it wishes, inside it’s code.
ü  If the inner class is public & the containing class as well, then code in some other unrelated class can as well create an instance of the inner class.
ü  can accept any accessibility modifiers
ü  they can be instantiated only in the context of an instance of the parent class
ü  can access all members of the enclosing class
ü  if a member in the inner class masks a member in the outer class (name collision) the inner class still has access to the outer class members: OuterClass.this.member
ü  if the inner class is public it can be instantiated from outside the outer class only using an instance of the outer class: outerInstance.new Inner()
ü  inner classes can be abstract or final
ü  hierarchies of inner classes can be created inside the outer class or inside classes that extend the outer class
ü  When inner classes are kept accessible only to the outer classes and their derived classes the syntax is pretty clear and the benefits for the design are clarity and better encapsulation. On the other hand, when inner classes are public, they can be used in surprising ways and the syntax starts to become less comprehensible. While there are creative ways to use public inner classes to solve real problems, the code for sure will start to lack in clarity and maintainability.

ü  No inner class objects are automatically instantiated with an outer class object.
ü  If the inner class is static, then static inner class can be instantiated without an outer class instance, otherwise, the inner class object must be associated with 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), if the inner class has a variable with same name then the outer class’s variable can be accesses like this:  <OuterClassName>.this.<variableName>
ü   The outer class can call even the private methods of the inner class.

Static Inner Classes:

Syntax for static inner class is as follows:
<access-specifier> class OuterClassName {
    public static class <StaticInnerClassName> { . . .  }   . . . }
For static inner classes following additional properties hold:
ü  Static members of the outer class are visible to the static inner class, whatever 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 classes are not referred 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 does not have the reference to its outer class object that generated it.
ü  is defined as a static member of the parent class
ü  accepts all accessibility modifiers
ü  it is NOT linked to an outer instance (it can live independently)
ü  has direct access to static members of the parent class regardless of the access modifiers declared in the parent class
ü  has direct access to all members of an instance of the parent class regardless of the access modifiers declared in the parent class

public class StaticInnerClass
{
    private static int staticCounter = 0;
    private int nestedCounter = 0;

    public static class Nested1
    {
        private static int staticCounter = 0;
        private int nestedCounter = 0;

        public static class Nested2
        {
            public Nested2(StaticInnerClass t, StaticInnerClass.Nested1 tn1)
            {
                     StaticInnerClass.staticCounter++;
                      t.nestedCounter++;
                      StaticInnerClass.Nested1.staticCounter++;
                      tn1.nestedCounter++;
              }
        }

        public Nested1(StaticInnerClass t)
        {
                  StaticInnerClass.staticCounter++;
           t.nestedCounter++;
}

        public String toString()
        {
            return
                getClass().getName() + ".nestedCounter: " + nestedCounter +
                System.getProperty("line.separator") +
                getClass().getName() + ".staticCounter: " + staticCounter;
        }
    }

    public String toString()
    {
        return
            getClass().getName() + ".nestedCounter: " + nestedCounter +
            System.getProperty("line.separator") +
            getClass().getName() + ".staticCounter: " + staticCounter;
    }

    public static void main(String[] args)
    {
       StaticInnerClass t = new StaticInnerClass();
       StaticInnerClass.Nested1 nested1 = new StaticInnerClass.Nested1(t); StaticInnerClass.Nested1.Nested2 nested2 = new
StaticInnerClass.Nested1.Nested2(t, nested1);

        System.out.println(t);
        System.out.println(nested1);
}
}


There are two more types of inner classes,
Local inner classes: The local inner classes are defined within a method.
Anonymous inner classes: Anonymous inner classes are also defined with in a method but have no name.

Local Inner Classes:


Local inner classes are declared inside of a block of code. This block can be static bloc, a constructor, a method or simply a block of code surrounded with curly braces. These classes are only visible inside the enclosing bloc, but inside the block full hierarchies of classes can be developed. Local inner classes can implement any interface or extend any class as long as those are visible and extendable. On the other hand interfaces cannot be declared in a local scope.
Local inner classes can access variables declared in the enclosing block as long as they are final. When the enclosing block is a constructor or a method the final parameters of the constructor or method are also accessible, of course for reading.
Members of the enclosing class are also accessible regardless of their access modifier. Keep in mind that a class declared in a static block can only access static members of the enclosing class.
Another interesting limitation is the fact that local inner classes cannot declare static blocks. Also a local inner cannot have the same name (hide) as an enclosing class.

ü  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 varible has to be declared final.
Example:
public class LocalInnerClass
{
    private static String s = "outer member";
    private int a = 1;

    static
    {
        final int b = 2;
        int c = 3;
        // local inner class in a static block
        final class LocalInner
        {
            public void f()
            {
                System.out.print(getClass().getName() + " inner in ");
                System.out.println(getClass().getEnclosingClass());
                System.out.println(s);
                System.out.println("b = " + b);
                // a = 2; // error: a is not static
                // c = 4; // error: a is not final
            }
        }

        LocalInner l = new LocalInner();
        l.f();
    }

    public LocalInnerClass(final String p1, String p2)
    {
        int a = 4; // hide the class member
        final int b = 5;

        // local inner class in a constructor
        class LocalInner
        {
            final String s2 = "inner member";
            public void f()
            {
                // declare a local inner in a method of a local inner
                class InnerInner
                {
                    public void f()
                    {
System.out.print(getClass().getName() + " inner in ");
System.out.println(getClass().getEnclosingClass());
System.out.println(LocalInnerClass.this.s);
System.out.println("bbbb---"+LocalInner.this.s2);
                    }
                }

System.out.print(getClass().getName() + " inner in ");
System.out.println(getClass().getEnclosingClass());
// direct access to members of the top level class
 System.out.println("s----"+s);
 // qualified access to hidden members of the top level class
 LocalInnerClass.this.a = 2;
 // access to variables declared in the enclosing block
 System.out.println(p1);
// System.out.println(s2); // error: p2 is not final
// a = 5; // error: a is not final
System.out.println("hai b = " + b);
// use the local inner
InnerInner i = new InnerInner();
i.f();
}
}
// use the local inner
LocalInner l = new LocalInner();
l.f();
}
public static void main(String[] args)
{
LocalInnerClass o = new LocalInnerClass("final param", "non-final param");
}
}

Anonymous Inner 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.
Anonymous class in Java is a class with no specified name declared and instantiated at the same time. Because it has no name it can only be used once at place of declaration. Anonymous classes implement an interface or extend a class. They cannot declare their own constructors (they don’t have a name known to the programmer) so the constructor used for instantiation is one inherited from the superclass. In the case where the the anonymous class implements an interface a no parameter constructor inherited from java.lang.Object is used.
Anonymous classes are given a name by the compiler and they are treated as local inner classes. This means that anonymous classes can access members of the enclosing class regardless of their access modifiers and they can access final variables declared in the enclosing block of code.

Such a class is called an anonymous inner class. Usually the inner class extends some interface or extends other class.
Example:
package com.shal.innerclass;


public class AnonymousInnerClass
{
    private String s = "test member access";

    public void test(final String s)
    {
        // anonymous instance as a variable
        Runnable r = new Runnable()
        {
              @Override
            public void run()
            {
                System.out.print(getClass().getName() + " inner in ");
                System.out.println(getClass().getEnclosingClass());
                System.out.println("in anonymous class 1");
                System.out.println(AnonymousInnerClass.this.s);
            }
        };

        Thread t1 = new Thread(r, "anonymous 1");

        // anonymous instance as a parameter
        Thread t2 = new Thread (new Runnable(){int a = 5;
        @Override
            public void run()
            {
                System.out.print(getClass().getName() + " inner in ");
                System.out.println(getClass().getEnclosingClass());
                System.out.println("in anonymous class 2");
                System.out.println(s);

                // anonymous instance inside another anonymous class
                Thread t3 = new Thread (new Runnable()
                {
                    @Override
                    public void run()
                    {
                       System.out.print(getClass().getName() + " inner in ");
                       System.out.println(getClass().getEnclosingClass());
                       System.out.println("in anonymous class 3");
                       System.out.println("a = " + a);
                    }

                });
                t3.start();
                try
                {
                    t3.join();
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }

        }, "anonymous 2");

        try
        {
            t1.start();
            t1.join();
            t2.start();
            t2.join();
}
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    public static void main(String[] args)
    {
        new AnonymousInnerClass().test("final parameter");
    }
}

ü  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 super class 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
o    new InterfaceType () { methods and data }



ü  It is recommended to refrain from using them as many programmers find too many anonymous classes hard to read.
The following table shows the types of nested classes:
Types of Nested Classes
Type
Scope
Inner
static nested class
member
no
inner [non-static] class
member
yes
local class
local
yes
anonymous class
only the point where it is defined
yes

                An inner class may not have static members unless the inner class is itself marked as static

 

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