Skip to content
Advertisement

How do you use anonymous objects with the factory pattern?

I have a method as so:

JavaScript

Now if I do this:

JavaScript

It’ll work perfectly fine. However, if I try to do this :

JavaScript

It doesn’t seem to work at all. It says “variable expected”.

I understand that new Foo() in itself, creates a new Foo object, but even if I use the factory, it should just override the anonymous object with a new Foo object.

I’ve also tried creating an ArrayList that holds Foo’s and doing

JavaScript

It still says “variable expected”. Why is it saying that?

JavaScript

This works perfectly fine, so I don’t understand why I can’t make the factory work with an anonymous object.

I tried searching for this online, but I got no search results, which tells me that I’m probably making some ridiculous mistake/using the factory pattern wrong.

Advertisement

Answer

Equals is an assignment operator.

JavaScript

new Foo() is statement that creates an object. It is a producer. You can’t assign anything to it, it’s not a variable reference. Variable references, like Foo foo =, are consumers. arraylist.get(0) is also a producer. that statement, just like a constructor, provides a value, but it is not a reference for you to assign something to. arraylist.add(object) is also a consumer.


I think you also misunderstand what an anonymous type is; an anonymous type is one where you override some or all of it’s behavior in-line, by specifying the new behavior after the class declaration with {}. For example:

JavaScript

You need an anonymous type because Runnable is an interface, there’s no behavior defined for run(), so Runnable r = new Runnable(); won’t compile.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement