0

On the subject of Anonymous classes, the Oracle documentation states that...

They are like local classes except that they do not have a name. Use them if you need to use a local class only once

Now, given that local classes are (to my knowledge) classes defined within a method (or some other local construct) like the following...(where 'MyInterface' is an interface with an abstract 'test' method)

public void localTest(){
    MyInterface mi = new MyInterface(){
        @Override
        public void test(){System.out.println("test");};
    };
}

The above is OK and falls within the definition above, however, I can also define the following...

class MyClass{

    MyInterface mi = new MyInterface(){
        @Override
        public void test(){System.out.println("test");};
    };
}

This isn't within a method so isn't a 'Local' class and therefore doesn't fall within the above definition. Is there anywhere I can read about these types of anonymous classes (anonymous member classes if you will). What exactly are they if not anonymous classes as defined?

8
  • 3
    They're still anonymous classes. What you've shown isn't a definition, it's an explanation - note the like local classes part. Even an anonymous class used in a field declaration is like a local class. Commented Mar 16, 2018 at 15:41
  • what if you change void localTest() to return MyInterface you will just publish variable that references your anonymous class - even if the reference can be accessed outside your method. So the class is still anonymous - it's local as you cannot have any other instances of this class. So the class is local (the object not necessary) Commented Mar 16, 2018 at 15:43
  • What you show is not a local class. Commented Mar 16, 2018 at 15:44
  • @LuiggiMendoza No, a local class is defined separately from its creation, both examples shown are simple anonymous classes. Local classes have an actual name. Commented Mar 16, 2018 at 15:46
  • When you add a field initializer on the field's definition, you're effectively adding a line of code to the default constructor. I'd guess that if you look at the compiled code there's probably an anonymous class getting associated with the constructor method. Commented Mar 16, 2018 at 15:49

2 Answers 2

1

Both examples you show are anonymous classes. A true local class is a class definition in a method (or other code block), with an actual name (so, not anonymous). Given your example, an equivalent local class would be:

public void localTest(){
    class LocalClass implements MyInterface {
        @Override
        public void test(){
            System.out.println("test");
        }
    }

    MyInterface mi = new LocalClass();
}

In my opinion you should hardly ever need a local class. I think I have only tried to use it once, to only quickly refactor it when I got a grip on what I actually needed.

The most important difference between local classes and anonymous classes is that you can reuse a local class within the same method (that is create multiple instances in the same method; without resorting to loops or lambdas).

Furthermore, as you actually have class definition, you can also define and call methods that aren't defined in the interface or super-class. Prior to Java 10 and the introduction of var, this was not possible with anonymous classes.

Other minor differences are that local classes can be abstract or final, and local classes can extend (and be extended by) other local classes, while an anonymous class is not final and cannot be abstract, but anonymous classes cannot be extended by other classes.

For more information regarding the difference between local classes and anonymous classes, see the Java Language Specification, specifically 14.3. Local Class Declarations and 15.9.5. Anonymous Class Declarations and related sections.

Sign up to request clarification or add additional context in comments.

6 Comments

Very good point on rarely (if ever) needing to use local classes. They add to complexity and detract from maintainability. Might be worth to note that conversely, anonymous classes can be extremely helpful.
@A.Bandtock To be honest, since Java 8 and method handles, I find I rarely need to use anonymous classes either.
Thanks, I'm trying to get the right terminology for the OCP exam. And also just because I just like to know the correct terminology. It's just confusing because anonymous classes are described as 'like local classes but without a name'.
That is because they are like local classes, but they have no name. Being like something does not mean it is the same.
Indeed @MarkRotteveel but it also says "They are like local classes except that they do not have a name. Use them if you need to use a local class only once, they are mentioning local classes very specifically.
|
0

Local classes are defined here as being defined in a block, rather than in a method. Your example is still an anonymous class. If you're in the process of learning, a note here is that you can actually replace the declaration with a lambda expression like so:

MyInterface mi = () -> System.out.println("test");

Also, anonymous classes are only described as being like local classes, meaning that the former is not necessarily a subset of the latter.

7 Comments

Hmmm... OK Thanks, @A.Bandtock. Are we really including the braces of a class here, if so, could you help me with understanding why we have the terms 'inner class' and' local class', when it would mean that all inner classes are local classes, (if I'm not mistaken) - seems a little superfluous...thanks - just trying to get my terminology right :-)
@Zippy Local classes are inner classes, but non-static classes nested inside another class are also inner classes (and those are far more common than local classes). See 8.1.3. Inner Classes and Enclosing Instances.
@Zippy If you read the link there, it actually gives you a definition of a block as "which is a group of zero or more statements between balanced braces", which basically translates to "anything between a { and a }. All local classes are inner classes, the distinction is as @Mark Rotteveel described.
I know that all local classes are inner classes, but this would also mean that all inner classes are also local classes, correct?
No, that interpretation is wrong. You have inner classes (non-static classes defined inside another class), and a small subset of inner classes (the 'special kinds') are local classes and anonymous classes; all others are 'normal' inner classes.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.