Anonymous class |
inner named class :
Link,
Link |
|
Inner anonymous class: Link,
Link |
Rules:
-
An anonymous class must always extend a super class or implement an
interface but it cannot have an explicit extends or implements clause.
(An independent parent)
- An anonymous class must implement all the abstract methods in the super class or the interface. (Must use all the methods of the parent with it's own.)
- An anonymous class always uses the default constructor from the super
class to create an instance.
(Uses parents licenses or credit cards)
|
Uses:
- Mostly used as a Comparator or creating object on the fly.
- Anonymous lasses had been used extensively used the past as to
implement listeners on GUIs.
|
In the example below, we see the steps how an
inner-anonymous class is called via method in a parent class, without
creating any instance of the anonymous class. This in contrast with the
named-inner class, since named has privileged with its own signature from a
method you need to create an object first.
|
Views of code snippet

 |
|
Example 1
import java.io.*;
import javax.swing.JOptionPane;
import java.net.URI;
public class ClassTemplate1 {
public ClassTemplate1()
// TODO Auto-generated constructor stub
}
public static void main(String[] args)
throws Exception {
// TODO Auto-generated method stub
Process pp = new Process();
// can't instantiate abstract class
try {
pp.read_line();
//
} catch (NumberFormatException exc) {
//
}
}
}// end of class template
//
//outer class
class Process
{
public Process()
{ System.out.println("Process outer constructor");}
public void read_line()
{
System.out.println("Reading Process outer class :");
//start of anonymous inner class
{
System.out.println
(" Process inner anonymous reader class ");
}//end of anonymous inner class
}//end read_line method
}//end of class process
|
 |
Example : 2 |
|
import java.io.*;
import java.util.*;//to use EnumSet, EnumMap classes
public class Test_This {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String str ="";
Process pp = new Process();
try{
System.out.print("Please write your name: ");
str = br.readLine();
pp.a_method(str);
}//try
catch(NumberFormatException e)
{ System.out.println("data was blank");}
}
}
class Process
{
public Process() { System.out.println("Process outer constructor");}
public int n2; String name="";
public void a_method(String str_method)
{
{
//contents of anonymous class
name = this.getClass().getName();
System.out.println("Received at anonymous inner class" + str_method);
}
System.out.println("Retreive class name at inner class: " + name);
}
//end method_1
}//end of class process
|
 |