0
Animal D = new Animal("Leo") {
                  @Override public void makeNoise() {
                        System.out.println("Roar!");
                  }
        };   
D.makeNoise();

So, when I asked what in this peaceful blue world this was, I was told that this was an anonymous class. I then looked up the related material and understood that they are classes with no name and are used only once. If that's the case, what is D? How come an anonymous class has a name 'D' here?

Secondly, do anonymous classes necessarily have to extend some other class (be it the cosmic Object itself)?

In my original code, Animal is actually an abstract class. What does this anonymous class have to do with Animal? Does it extend the Animal abstract class?

Trent Boult
  • 117
  • 3
  • The confusion is that anonymous classes aren't necessarily used once but they are defined once. This can be convenient if the class needs to used in one place –  Mar 02 '15 at 02:21
  • I closed this as a duplicate, even though I agree that the answers on your original questions leave a bit to be desired, so I understand the need for a follow-up. In particular, I think those answers really should be improved to explain everything in this thread as well. – Thilo Mar 02 '15 at 02:23
  • Voting to repoen. It is **not** a duplicate of *that* question. The questions are fundamentally different; even if one follows the other. (I am sure this can be closed as *a* duplicate with some digging, but..) – user2864740 Mar 02 '15 at 02:23
  • See http://stackoverflow.com/questions/21869294/in-java-what-is-the-relationship-of-an-anonymous-class-to-the-type-it-is-defined , http://stackoverflow.com/questions/8355286/type-of-anonymous-type – user2864740 Mar 02 '15 at 02:25
  • Ok, we have a confusion here. Is D an instance of the anonymous class or is it a reference variable to type Animal that points to an anonymous class? – Trent Boult Mar 02 '15 at 02:30
  • @TrentBoult the anonymous class points to Animal no more and no less than Animal points at Object. Being an anonymous class does not provide any more indirection then simple inheritance provides. It doesn't really give you much of anything beyond the lack of any responsibility to give it a name. But being free of that responsibility can make for more much more expressive code. – candied_orange Mar 02 '15 at 03:14

5 Answers5

2

D is a variable representing a value/object conforming (read: "assignable to") to an Animal.

The actual object assigned is a new instance of an anonymous type which is actually a subtype of Animal.

user2864740
  • 60,010
  • 15
  • 145
  • 220
  • Can I just say that D is a reference variable of type Animal (as it points to an animal usually) that points to an anonymous class that extends Animal? – Trent Boult Mar 02 '15 at 02:26
  • @TrentBoult Yes, that's right. Note that your anonymous class `D` is also still an `Animal`. – m0skit0 Mar 02 '15 at 02:27
  • @TrentBoult Yes; D is a variable and the anonymous class shown [implicitly] extends Animal. (Although I personally do not like the phrasing 'reference variable'.. :) – user2864740 Mar 02 '15 at 02:32
  • Ok, thanks. As it hold a reference to an Animal object, I called it a reference variable, but I see that it can be misleading. – Trent Boult Mar 02 '15 at 02:35
  • @user2864740 I don't agree. I think *reference variable* is correct. It is a reference, and you can assign it to another reference if needed, hence *variable*. Although yes, it is commonly referred as *reference* only. – m0skit0 Mar 02 '15 at 02:43
  • @m0skit0 The problem with 'reference variable', IMOHO (and I program in a number of different languages) is that it forces having to "think in references". References (and references values and properties that store reference values) are merely a leaky implementation detail. By avoid using 'reference [variable]' as much as possible the focus can be kept on a universal "high level view". Which is, objects (a subtype of values) are objects and assignment (in languages like Java and C# and JavaScript and Python and even SML and..) of such 'reference types' does not create a copy of said object. – user2864740 Mar 02 '15 at 02:46
  • @m0skit0 And because of then only keeping 'reference [..]' for special cases I can include languages like C++ in the discussion (which has an entirely different underlying philosophy), or reference specification types in JavaScript, or ref/out in C#) when the case warrants.. or even about talking about the low-level JVM. – user2864740 Mar 02 '15 at 02:48
  • @user2864740 IMHO those leaky implementation details are (sadly) of vital importance to beginners. If you say that `D` is the object, then confusion arises, like [here](http://stackoverflow.com/questions/15292980/java-arraylist-pass-by-reference). – m0skit0 Mar 02 '15 at 02:49
  • @m0skit0 The confusion is caused by *not* teaching beginners these rules: 1) an object is itself; 2) neither an assignment nor a method call make a copy/clone/duplicate of an object. (The remaining details are smoothed out when discussing mutable vs immutable values/types.) The universally applicable term for such behavior is Call By Object Sharing. – user2864740 Mar 02 '15 at 02:50
  • @user2864740 It's easier and safer if they think of them as references, not memorizing rules without knowing why, but that's just my opinion. I'm not a big fan of memorizing stuff :) – m0skit0 Mar 02 '15 at 02:51
1

If that's the case, what is D? How come an anonymous class has a name 'D' here?

That's not the class name, that's a variable/reference name for the anonymous class.

Secondly, do anonymous classes necessarily have to extend some other class (be it the cosmic Object itself)?

Yes, in Java all classes extend from Object. It can also implement an interface (besides extending Object of course). A typical interface to implement is Runnable.

    final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // Does amazing stuff
        }
    };

What does this anonymous class have to do with Animal? Does it extend the Animal abstract class?

Yes, it extends Animal, which in fact means it is an Animal (check polymorphism).

m0skit0
  • 25,268
  • 11
  • 79
  • 127
  • Cheers buddy. Why do you say that the Animal class has to be abstract in your last line? – Trent Boult Mar 02 '15 at 02:29
  • Also, can I just say that D is a reference variable of type Animal (as it points to an animal usually) that points to an anonymous class that extends Animal? – Trent Boult Mar 02 '15 at 02:29
  • Sorry, my mistake, it doesn't have to be abstract, fixed it. And yes, `D` is a reference variable of type Animal that points to an anonymous class that extends Animal. – m0skit0 Mar 02 '15 at 02:31
  • Thank you. Just one last doubt. Is D better off described as an instance of the anonymous class or what I said in my last comment? – Trent Boult Mar 02 '15 at 02:38
  • In fact in Java you never deal with instances themselves, only with references to those instances, even if sometimes they are used interchangeably. This means the object is allocated in memory when you instantiate it, and you manipulate it through the returned reference (`D` in this case). – m0skit0 Mar 02 '15 at 02:41
  • Got it. Thanks a lot once again. – Trent Boult Mar 02 '15 at 03:01
0

D is an instance of Animal. It is also an instance of your anonymous class. It is also an instance of Object. That's how inheritance works. It also shouldn't be capitalized. Use d and you'll be conforming to the style guidelines.

Here's your inheritance chain. You can't cast it to an anonymous class but that's not going to stop the anonymous class from overriding the makeNoise() method.

Object
   ^
   |
Animal
   ^
   |
This Anonymous Class
candied_orange
  • 7,036
  • 2
  • 28
  • 62
  • 2
    D is an _instance of_ the anonymous class which extends Animal. It isn't the anonymous class. – Adrian Leonhard Mar 02 '15 at 02:19
  • Are you sure D is an instance of the anonymous class and not a reference variable of type Animal that points to an anonymous class of type animal ? – Trent Boult Mar 02 '15 at 02:31
  • 1
    @TrentBoult If you put that fine a point on it yes. The anonymous class has no name. Any instance of any class also has no name. They have addresses. Addresses are a pain to remember so we don't deal with them directly in Java. Strictly speaking `D` is an identifier. This identifier is associated with an address. The memory at that address is the reference. That memory contains another address (when it's not `null`) that is the address of the instance. When I say `D` is an instance I am dereferencing that reference. – candied_orange Mar 02 '15 at 03:20
0

The class is actually a subclass which extends Animal. The brackets, which, inside is the implementation of the class, indicates that the makeNoise is being overwritten.

For the second question, yes, mostly the anonymous class occurred when you want to inherit a class and modify some implementations, but you don't want to claim a new class in detail as it is really short, or just by convenient.

LynxZh
  • 825
  • 5
  • 9
0

Yes, anonymous classes have to implement interface or extend existing class. Actually, D is not an Animal itself; it belongs to subtype of Animal.

public class Main {
    public static void main(String[] args) {
        Object a = new Object() {
            @Override
            public String toString() {
                return "";
            }
        };
        System.out.println(a.getClass().toString());
        System.out.println(new Object().getClass().toString());
    }
}

This code gives:

class Main$1

class java.lang.Object

Community
  • 1
  • 1
Everv0id
  • 1,862
  • 3
  • 25
  • 47