-5

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();

    }

}
bigcodeszzer
  • 916
  • 1
  • 8
  • 27
  • How is the example with `FileNameFilter`, where content is just `return s.endsWith(".java");` *over-complicated*? – Andreas Jul 20 '16 at 20:40
  • 1
    *"absolute minimal requirements to define a anonymous class"*: An interface or a non-final class. – Andreas Jul 20 '16 at 20:41
  • @Andreas Because the code instantiates an entirely other class File, which is presumably part of the Java libraries. The entire example is written within .list() method of the file instance. Anonymous classes do not require File or File.list() so the example is not minimal. – bigcodeszzer Jul 20 '16 at 20:45
  • @Andreas The syntax they later provide in this document is `new class-name ( [ argument-list ] ) { class-body }` The syntax does not make reference to an instance of any kind making the inclusion of an instance within their example all the more non minimal – bigcodeszzer Jul 20 '16 at 20:51
  • 1
    The purpose of an anonymous class is to be *used* by something. `File.list()` is a *very* simple example of a method that can use an anonymous class. WHat is the point, if it doesn't take input or produce output? `File` is a *very* common Java class, and a *great* example for the purpose. Sure, the example is more than a useless do-nothing implementation, but it is hardly *over-complicated*. – Andreas Jul 20 '16 at 20:51
  • Granted, non-minimal rather than over-complicated. Edited. – bigcodeszzer Jul 20 '16 at 21:05
  • Edited...... this is what I mean – bigcodeszzer Jul 20 '16 at 21:24
  • So you prefer useless examples that have no meaning or purpose? Then drop both `var1` and `extendedVariable`. That would make it equally useless, but at least won't confuse you, trying to figure out what the point of it is. – Andreas Jul 20 '16 at 21:28
  • @Andreas Edited again. – bigcodeszzer Jul 20 '16 at 21:58

5 Answers5

2

The most minimal example:

interface Foo {}
public static void main (String[] args)
{
    Foo foo = new Foo() {};
}

Literally a declaration of an interface, and then usage as an anonymous class with no additional declarations.

Practically speaking, it does nothing. However, as we add bits in:

interface Foo {
    public void bar();
}
public static void main (String[] args) throws java.lang.Exception
{
    Foo foo = new Foo() {
        public void bar() {
            System.out.println("Hello");
        }
    };
}

It becomes a full-fledged helper class for our method.

The most common use for early/mid level programming would be overriding Listeners to do specific actions. We know the Listener is listening for something, and we want it to do something as a result of the Listener, so we craft the Listener and say "Do this when you are triggered."

Here's the example of a really complex ActionListener tutorial: https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

But typically, if it's something that's mundane like "run a method on click", you'll use an anonymous in-line declaration that just calls a method for you.

Compass
  • 5,867
  • 4
  • 30
  • 42
  • You should remove `throws java.lang.Exception`. If things like [using a `File`](http://stackoverflow.com/questions/38490376/java-anonymous-class-minimal-example?noredirect=1#comment64382701_38490376) is over-complicated for OP, then exceptions are likely incomprehensible. But, +1 for starting simple. – Andreas Jul 20 '16 at 21:01
  • @Andreas yeah it was left over from ideone and I didn't notice it, scrubbed. – Compass Jul 21 '16 at 14:32
1

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";
     }
}
Zircon
  • 4,677
  • 15
  • 32
0

How about this example?

//interface
interface Message{
   String greet();  
}

Message is a anonymous class in this example, greet() is the only method inside this anonymous class.

//Passing an anonymous inner class as an argument
      obj.displayMessage(new Message(){
         public String greet(){
            return "Hello";            
         }
      });
Sundararaj Govindasamy
  • 8,180
  • 5
  • 44
  • 77
0

As Compass has already said, the absolute minimum is not useful.

Following is an example of a 'useful' inner class:

JButton ok = new JButton();
    ok.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("abc");

        }
    });

So instead of having to define an inner class or a helper class for an ActionListener you only use once, you can just have it as an inline or anonymous class to remove clutter and increase readability.

Meik Vtune
  • 450
  • 8
  • 25
0

You can think of an anonymous class as just basically the instantiation part of creating a new instance of an object. You essentially just don't declare it and give it a name. This is normally passed into method parameters as shown below.

Object someObj; is an object declaration. someObj = new Objct(parm a,...) is the instantiation of the object.

    //example of anonymous classes:
    public void foo(Bar barObj){// takes a Bar object parameter
         //does stuff
    }

    //you can call the foo method in this way
    Bar barObject= new Bar();
    foo(barObject){}
    // or you can call the Bar anonymously
    foo(new Bar()){}

In the anonymous example you instantiate a new Bar inside the method parameter. You can do this when you just need something local and don't need it to be used anywhere but in that method call. it also then gives you access to the accessible methods that are inside of the anonymous class. so you could do something like

foo(new Bar().barMethod){}. It just kind of depends what you are working with.