What benefit do method-local inner classes provide in Java?
Asked Answered
S

6

9

I've just read through the chapter on method-local inner classes in the SCJP book, and I'm really struggling to think of any practical use for them.

I've always been under the impression, that methods should be as small and specific to their task as possible (Orthogonality IIRC), so introducing even the simplest inner class would create heft and unwieldy methods.

Can anyone suggest a good practical usage for method local inner classes? So far it feels as if I might have to understand them purely for passing the exam, and not for use in everyday coding.

Cheers

Springy answered 4/4, 2011 at 19:39 Comment(3)
They are often used for implementing callback methods.Hedgehog
I used them only one time so far: I needed a suitable key class for a temporary HashMap in a method.Gottwald
Real world method local innerclass usage here: https://mcmap.net/q/519305/-why-use-method-local-abstract-inner-classesForgiving
S
12

In most cases (e.g. for action listeners, runnables and such) you would use anonymous classes instead of method-local named classes.

But there is one thing which named classes can do and anonymous classes can't: implementing more than one interface, or extending a class and interfaces, too. Also, you can create more than one object of this class (without using a loop).

Shorts answered 4/4, 2011 at 19:54 Comment(2)
"Also, you can create more than one object of this class (without using a loop)." - You sure can. Even across multiple calls of the method that defines the class, the class is still the same.Rosy
Although this proves reason as to why may it exist (implementing multiple interfaces), but it doesn't express practical use. Is there a reason for declaring a class within a method? I haven't seen any examples from the open jdk yetAtop
T
4

I'd say that better encapsulation is the benefit.

Teddman answered 4/4, 2011 at 19:43 Comment(0)
U
2

Method local inner classes are useful when you are trying to do "functional" operations, or passing code to another object to be called later. In most cases classes like these are only called or used once, so there is no need to define it somewhere else and force the reader to go hunting for it. Future versions of Java are likely to replace most use cases for these types of inner classes with "closures".

Common cases are when you are writing an event listener that calls some other method or starting a new thread.

Unload answered 4/4, 2011 at 19:45 Comment(1)
For which use anonymous classes instead of method-local named classes are better.Boni
H
1

Local classes allows to take logic out of the parent class and objectify it. This removes functionality from where it doesn't belong and puts it into its own class. But what if this new object is only needed for a short time, only for the duration of a single block of code? Well, that's where a local class fits in.

Holocrine answered 4/4, 2011 at 19:43 Comment(0)
C
0

I think of Runnable implementation passed to Thread:

Thread t = new Thread(new Runnable() {
   void run() {
      ...
    }
});

This is anonymous class, and any anonymous class is inner as well.

Chu answered 4/4, 2011 at 19:50 Comment(1)
but runnable is not a method local inner class (it is a plain anonymous inner class)Chaco
P
0

The local classes (method local inner classes) are rarely used. It can be useful when any repeated functionality is required inside a method and if we are NOT interested to create class level method (may be because this functionality we may not require outside of method) for example, lets assume sum & mul methods are repeatedly require in our code (any particular method), one way to create a class level methods and call them whenever required, but what if these methods no longer required outside this method, in this case we may think of creating a local inner class and access its sum method whenever required only within that method, below example

class Outer {
    public void calculations() { 
        class Inner {
            public int sum(int x, int y) {
                System.out.println("sum : " + (x+y));
                return x+y;
            }
            public int mul(int x, int y) {
                System.out.println("multiplication : " + (x*y));
                return x*y;
            }
        }
        Inner i= new Inner();
//some code...
        i.sum(10, 20);
//some code...etc
        i.mul(30, 40);
        i.mul(14, 12);
        i.sum(10000, 20000);
//some other code...
    }
}
public class TestClass {
    public static void main(String[] args) {
        new Outer().calculations();
    }
}
Paten answered 17/7, 2018 at 17:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.