Anonymous Inner class
nameless or without any identity is called anonymous.
To override the method in outer class of the inner class object.
Different ways of implement Anonymous Inner classes :
- using Concrete class
- using Abstract class
- using Interface
- as method argument
Why we use
In java 8, Lambda expression and Functional interface can be understand by these concepts.
Example Anonymous Inner class Using Concrete class
I have a class named as parent and another class named as child. child extends the parent class. So parent class method can be access by child class depends on access modifier.
public class parent { public static void main(String[] args) { child a = new child(); a.educate(); a.leave(); a.salary(); } public void educate() { System.out.println("education"); } public void leave() { System.out.println("leave"); } public void salary() { System.out.println("90000"); } } class child extends parent { public void salary() { System.out.println("10000"); } }
Output
education leave 10000 |
if we remove salary method in child then the output is
education leave 90000 |
But the child need it own method definition go for anonymous inner class
code
parent a = new parent() { public void salary() { System.out.println(20000); } };
it is use to give a method for a single object. it must be end with ; (semicolon) like above code.
note : we can define method in inner class which are define in outer class.
Reference :
https://www.geeksforgeeks.org/java/anonymous-inner-class-java/