Before beginning this post, I would like to state that this post assumes some prior knowledge of Java (particularly inheritance, using interfaces and overriding methods)
Most classes we have seen have their own name and exist on their own (outside any other class or method). But anonymous inner classes can exist inside another class/method, and do not have a name (hence the name ‘anonymous’). These classes must either extend another (named) class or implement an interface. When the interface being implemented has only one abstract method, the anonymous inner class can be converted into a special expression called a lambda expression (as of Java 8), which simplifies the code. This post talks about anonymous inner classes and lambda expressions in detail.
Anonymous Inner Classes
As mentioned above, anonymous inner classes do not have a name, can exist within another class/method, and must extend another class or implement an interface.
Let us see the various examples that can be used to work with anonymous inner classes:
- The following example uses an anonymous inner class to extend another class and create an object of it on the spot. Observe the syntax carefully:
//Using anonymous inner classes to override methods of an existing class
package codingexamples;
class Sample{
public void display(){
System.out.println(“Sample”);
}
}
public class Example1 {
public static void main(String[] args){
Sample s1 = new Sample();
Sample s2 = new Sample() { //line 1
public void display(){
System.out.println(“Sample 2”);
}
}; //this semicolon is very important
useSample(s1);
useSample(s2);
}
static void useSample(Sample s){
s.display();
}
}
The output of the above code is:
Sample
Sample 2
Observe the bold section of the code carefully. Note that the first line of code in this region ends in a curly brace, not a semicolon. This line declares a reference variable of type Sample, and initializes it with an object whose type is not Sample, but an anonymous subclass of Sample. The curly brace at the end of the line is the start of the anonymous inner class body.
The next three lines of code, as we can see, are overriding the display() method in the class Sample. This is, of course, the reason behind creating anonymous inner classes. The last line of (bold) code requires some attention. The closing curly brace marks the end of the class, but that’s not all – there is also a semicolon to end the statement started on line 1! As it is unusual to see semicolons after closing braces, this is very easy to miss.
On the whole, the code creates two Sample references, one holding a Sample object, and another holding an object of an anonymous subclass of Sample (which overrides display()). These variables are then passed to the useSample() method which calls their respective display() methods. This leads to the output mentioned above.
2. Anonymous inner classes implements an interface in the second example:
//Using anonymous inner classes to implement methods of an interface
package codingexamples;
interface Movable{
void move();
}
public class Example2 {
public static void main(String[] args){
Movable m1 = new Movable(){
public void move(){
System.out.println(“m1 is moving”);
}
};
useMovable(m1);
}
static void useMovable(Movable m){
m.move();
}
}
The output of the above code is, as expected:
m1 is moving
This code is very similar to the first example. Note that even though the syntax used is ‘new Movable()’, the code is not instantiating the interface (it’s not legal to do so). The variable m1 refers to an anonymous implementer of Movable.
3. Anonymous inner classes can extend/implement classes/interfaces having more than one method as well. They can also be used as method arguments (watch the syntax again). The following example illustrates these two points:
//Another example of anonymous interface
package codingexamples;
interface Bounceable{
void bounce();
void jump();
}
public class Example3 {
public static void main(String[] args){
/* Create an anonymous implementer of Bounceable in the argument list of useBounceable() */
useBounceable(new Bounceable(){
public void bounce(){
System.out.println(“Anonymous object bouncing”);
}
public void jump(){
System.out.println(“Anonymous object jumping”);
}
});
}
static void useBounceable(Bounceable b){
b.bounce();
b.jump();
}
}
The output of the above code is:
Anonymous object bouncing
Anonymous object jumping
Observe how the object of the anonymous inner class is created right inside the argument. Also note that in this case, the statement ends with a closing curly brace, a closing parenthesis and then a semicolon.
Lambda Expressions
Now we will move onto Lambda expressions. Consider the following scenario. You have a class Student, which stores some details of a student such as name, marks etc. You also have an interface Check, as shown below:
interface Check{
boolean test(Student s);
}
This is meant to create multiple custom ‘checks’ on the attributes of each student (for example, ‘name’ starts with ‘A’, ‘marks’ >= 95 and so on). For each such test condition, prior to Java 8, it would be necessary to define a class that implements the interface. Of course, it would be inconvenient to define multiple such implementers with names such as ‘CheckName’, ‘CheckMarks’ etc. (as one can see, it is repetitive). Another approach is to use anonymous inner classes as implementers of interface Check (already discussed above), which removes the problem of repetitive names. However, each anonymous implementer, as we have seen already, spans at least five lines of code.
Java 8 allows you to create ‘instances’ of functional interface ‘implementers’ through the use of lambda expressions (a functional interface is one that contains exactly one abstract method). These can, in certain cases, replace anonymous inner classes and simplify the code. The following example defines the class Student, interface Check and makes use of the interface through lambdas:
//Demonstrate the use of lambda expressions
package codingexamples;
class Student{
private int marks;
private int grade;
private String name;
public Student(String n, int m, int g){
name = n;
marks = m;
grade = g;
}
public String getName(){
return name;
}
public int getMarks(){
return marks;
}
public int getGrade(){
return grade;
}
}
//Check is a functional interface (one abstract method)
interface Check{
boolean test(Student s);
}
public class Example4 {
public static void main(String[] args){
Student[] students = {
new Student(“John”, 90, 7),
new Student(“Roger”, 70, 9),
new Student(“Fred”, 88, 6),
new Student(“Robert”, 60, 8)
};
//Lambda expressions
Check seniorsChk = s -> s.getGrade() >= 9;
Check toppersChk = s -> s.getMarks() >= 85;
System.out.println(“Senior students:”);
filterStudents(students, seniorsChk);
System.out.println();
System.out.println(“Toppers:”);
filterStudents(students, toppersChk);
}
static void filterStudents(Student[] stu, Check chk){
for(Student s: stu){
if(chk.test(s))
System.out.println(s.getName());
}
}
}
The output of the above code is:
Senior students:
Roger
Toppers:
John
Fred
Before going into the working of this code, let us observe the syntax of the lambda expression. The general syntax of a lambda expression is:
<Parameter(s)> <Arrow> <Lambda Body (must be an expression which evaluates to the abstract method’s return type)>
To understand better, keep in mind that the following expression:
s -> s.getGrade() >= 9
Is equivalent to (in this case):
new Check(){
public boolean test(Student s){
return s.getGrade() >= 9;
}
}
Thus a lambda expression essentially just behaves like an anonymous inner class, with fewer lines of code. Now we can understand that the code basically creates two ‘test conditions’ on Student objects, using lambdas, and then filters a list (array) of Student objects using these ‘test conditions’ (implementers of interface Check). Walk through the lines of code to understand better. Here, Roger is considered a senior as he is in a grade higher than or equal to grade 9, and John and Fred are considered toppers as each of them has scored more than or equal to 85 marks each.
Before we end, let us rewrite the code in Example 2 using a lambda expression (interface Movable used in that example is also a functional interface). Old code is commented out:
//Example 2 rewritten using a lambda expression
package codingexamples;
//assuming interface Movable already exists
public class Example5 {
public static void main(String[] args){
/* Movable m1 = new Movable(){
public void move(){
System.out.println(“m1 is moving”);
}
};
*/
Movable m1 = () -> System.out.println(“m1 is moving”);
/* note that parentheses are needed when the method
accepts zero arguments or more than one argument */
useMovable(m1);
}
static void useMovable(Movable m){
m.move();
}
}
The output of the code remains the same as before. Note that examples 1 and 3 above cannot be rewritten using lambdas, as example 1 uses a class, and example 3 uses a non-functional interface (two abstract methods).
We have seen different types of anonymous inner classes and Lambda expressions in this post… stay tuned for more technical posts!
this is obviously foreign language to me, good luck for your work
🙂 🙂