Monday, 30 January 2017

ANONYMOUS OBJECT IN JAVA

When we don’t know something name then we call it as anonymous. Suppose we met a person and we don’t know his name then we say that he was a anonymous person. Basically anonymous object is used in such condition when we need to call some method only once. Because when we create an object the memory will be allocated inside stack as well as heap. But if we have to use a object only once then we will use anonymous object which creates memory only inside heap memory. 

Suppose if we have 10000 lines of code and there is one object at line 1000 which is used to invoke some method only once then unless 1000 line of code as we are not using that particular object but still it is referring to heap memory. And after line 1000 that object is eligible for garbage collection. So the main concept behind using anonymous object is that when we need to use that particular object only once. We should not use anonymous object for multiple process because all the time we call it, it creates a new memory inside heap and reference to that not the earlier one.

Example –
class Abc{
          public void show()
          {
                   System.out.println("Hello java");
          }
}
class Tesr1 {
          public static void main(String[] args) {
                   new Abc().show();
          }
}

Output –
Hello java


Example –
class Abc{
          int k;
          public void show()
          {
                   System.out.println(k);
          }
}
class Tesr1 {
          public static void main(String[] args) {
                   new Abc().k=9;
                   new Abc().show();               
          }
}

Output –
0


Note – In the above example we have seen that even we have assigned value for k as 9 but we get the value as 0. Because whenever we create anonymous object it create new memory inside heap and reference to that.

No comments:

Post a Comment