Anonymous Object
- Eclipse: Oxygen
- Java: 1.8
The anonymous object simply means creating a new Object without assigning it to a reference. Hence this could be used only once in the execution of a program as it is not referenced to any object.
It is useful for writing implementation classes for listener interfaces in graphical programming.
Let us take a simple program, to understand an anonymous object.
Here, an object for Door class is not created. We can create a new Object without assigning it to a reference.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class Door { public boolean isLocked(String key) { class Lock { public boolean isLocked(String key) { if (key.equals("qwerty")) { return false; } else { return true; } } } return new Lock().isLocked(key); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Public class Shop { public static void main(String[] args) { //Door door = new Door(); if(new Door().isLocked(args[0])) { System.out.println("Shop has closed, visit later"); }else{ System.out.println("Welcome, we are open :)"); } System.out.println(args[1]); System.out.println(args[2]); } } |
Contributed by: Poonam Tomar