bigcodeszzer bigcodeszzer - 4 months ago 20
Java Question

Java Anonymous Class - minimal example

I'm trying to understand Java anonymous classes.

Looking here:
https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

And here:
http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm

I understand the basic syntax, but the examples are non-minimal.

What are the absolute minimal requirements to define a anonymous class in Java?

Edit>>>

Essentially this:

public class MyClass {

InnerClass instance = new InnerClass();

public class InnerClass{

public void print(){
System.out.println("First Call");
}
};


public void redefineInstance(){

instance = new InnerClass(){

public void print(){
System.out.println("Second Call");
}

};
}

public static void main(String[] args) throws Exception{

MyClass myobject = new MyClass();
myobject.instance.print();
myobject.redefineInstance();
myobject.instance.print();

}

}

Answer

I suppose the "absolute minimal requirement" to create an anonymous class is to have a place in your code that requires an instance of a non-final class or interface of some kind.

Meaning, if I have a method in MyClass:

public static void gimmeMyObject(MyObject c)

I can define an anonymous class that extends MyObject as long as MyObject is not final:

//Somewhere in a method
MyClass.gimmeMyObject(new MyObject() {
      public String myMethod() {
           return "I'm anonymous";
      }
});

That anonymous class will be passed in as a MyObject.

However, I could not do this if the method required a String or Integer, for example, because those are final classes.

For the above example, the non-anonymous class would translate to:

public class MyAnonObject extends MyObject { //In actuality, an anonymous class doesn't have a name, though.

     public String myMethod() {
           return "I'm anonymous";
     }
}