Search code examples
javainner-classesanonymous-class

Can I call methods of anonymous classes in any time?


I saw this sample code:

public class Main{ 
    public static void main(String[] args){
        Pocket<Object> pocket = new Pocket<Object>;
        System.out.println("test");
        pocket.put(new Object(){
            String field;
            void inner(){
               ...
            }
        });
    }  
}

Anonymous-classes doesn't have a class name. So I thought "How do I call anonymous class in any time?" while I'm reading this code.

As per title, Can I call methods of anonymous classes in any time? If I can, how do I call?

PostScript

Object is java.lang.Object.


Solution

  • In Java, anonymous classes are meant for providing implementations for a class within a method (or a block of code).

    However, they make the code harder to read/maintain because of their verbosity.

    For example, if you have an interface like Product as below:

    public interface Product {
      void display();
    }
    

    In some other class, you can implement the Product interface as follows:

    public class Test {
    
      public void static main(String[] args) {
    
         Product product = new Product() {
    
                @Override
                public void display() {
                    //add your code to display
    
                }
            };
    
        //now using reference, you can call display()
        product.display();
    }
    

    }

    Now, coming to your code, you can override java.lang.Object methods as shown below:

    pocket.put(new Object(){
    
                @Override
                 public String toString() {
                     return "My Object String";
                 }
    
                 //You can override other methods of java.lang.Object
    
                 //note that, because your reference type is java.lang.Object, 
                 //so you will NOT be able to call inner(), 
                 // 'field' members even if you add them here
            });
    

    Can I call methods of anonymous classes in any time? If I can, how do I call?

    You need the reference to call the methods/members (as like any other object inocation) implemented through anonymous class so, product.display();will invoke the display() method. Or in your case, you can call like pocket.get(i).toString() or any methods of java.lang.Object

    As a side note, remember that, in Java8, you can replace Anonymous classes with Lambda expressions provided you have only one abstract method to implement.