Anonymous Inner Class
Anonymous inner class is without having any name such type of class is called anonymous inner class.
Example 1.
Runnable r = new Runnable (){
public void run () {
}
}
Note: -
- Anonymous inner class that extends concreate class.
- Anonymous inner class that extends Abstract class.
- We can declare instance variable with in the anonymous inner class.
- Anonymous inner class is not equal to Lambda expression.
Note:- this.x always refers to inner variable in anonymous inner class.
interface InterfB{
public void m1();
}
public class TestAnonymous {
int x=10;
public void m2(){
InterfB interfB = new InterfB() {
int x=20;
@Override
public void m1() {
System.out.println(this.x);
}
};
interfB.m1();
}
public static void main(String[] args) {
TestAnonymous testAnonymous = new TestAnonymous();
testAnonymous.m2();
}
}
Result:- 20
Note:- this.x lambda expression refers outer variable only.
Example 2.
interface interfC{
public void m1();
}
public class TestwithLambda {
int x=10;
public void m2(){
interfC i = ()->{
int x=20;
System.out.println(this.x);
};
i.m1();
}
public static void main(String[] args) {
TestwithLambda lambda = new TestwithLambda();
lambda.m2();
}
}
Result:-10
Example 3. With Anonymous function using Thread.
public class ThreadWithAnonymousDemo {
public static void main(String[] args) {
Thread t= new Thread(()->System.out.println("Child Thread"));
t.start();
for(int i=0; i<10; i++){
System.out.println("Main Thread");
}
}
}
Example 4. With Lambda Expression.
public class ThreadWithAnonymousDemoUsingLambda {
public static void main(String[] args) {
Runnable r = new Runnable(){
@Override
public void run() {
for(int i=0; i<10; i++){
System.out.println("Child Thread");
}
}
};
Thread t = new Thread(r);
}
}
Difference between Anonymous inner class and Lambda Expression
Anonymous inner Class
- It is a class without name.
- Anonymous inner class can extends Abstract class and Concrete classes.
- Anonymous inner class can implements as interface that contains any number of abstract methods;
- Inside Anonymous inner class We can declare instance variable.
- Anonymous inner class can be instantated.
Lambda Expression
- It is function without name (Anonymous function).
- Lambda Expression can’t extends Abstract class and Concrete classes.
- Lambda Expression can implement as interface which contains single abstract method(Functional Interface) .
- Inside Lambda Expression we can declare instance variable what ever variable declared are consider as local variables.
- Lambda Expression cannot be instantiated.
0 Comment to "Anonymous Inner Class in Funcational Interface"
Post a Comment