Anonymous inner classes are little confusing in java. Remember one thing about these classes that, anonymous inner classes can either implement one interface or extend one class at a time only. These classes can never extend and implement class and interface but only one at a time.
Here I am presenting few things about anonymous inner classes with examples.
Anonymous inner class extending class :
Here is a code where anonymous class is sub class of one of super class,
Code :
class Test {
public void cool() {
System.out.print("This is original.");
}
}
class Main {
public static void main(String args[]) {
Test t = new Test() {
public void cool() {
System.out.print("This is duplicate.");
}
};
t.cool();
}
}
This code will output "This is duplicate.". In this way we can use anonymous inner classes for overriding one or more methods of super class.
Anonymous inner class implementing interface :
Here is code presenting this concept,
Code :
interface Test {
public void ohh();
}
class Main {
public static void main(String args[]) {
Test t = new Test() {
public void ohh() {
System.out.print("Hahahaha");
}
};
t.ohh();
}
}
}
This code will print "Hahahaha". Here anonymous inner class is implementing our Test interface.
Anonymous inner class as argument :
Here is code for this one,
Code :
----------
----------
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEent ae) {
}
});
---------
---------
Enjoy it.....
No comments:
Post a Comment