0

So we know that Java 8 method references can be used to replace anonymous class creation. I'm curious if there's a way to use them to define named classes that implement a functional interface, something -- vaguely -- along the lines of

   public interface Bar {
       String returnSomeString();
   }

   public class Foo implements Bar = someObjectInstance::toString;

I know you can't use equals in defining a class, but something like that...

anqit
  • 780
  • 3
  • 12
  • define a *class* ? no. define an *object*, yes. – Nir Alfasi Sep 06 '17 at 00:36
  • 5
    `Bar foo = someObjectInstance::toString;` – Brian Goetz Sep 06 '17 at 00:40
  • @BrianGoetz, so that's creating an instance of an anonymous implementation of `Bar`, like @alfasin said, correct? But say this was an instantiation that was happening often enough, or in some other situation where anonymous classes were undesirable, it would be nice to be able to use a method reference to define a named class. But it seems that that is not possible... – anqit Sep 06 '17 at 00:57
  • Why would anonymous classes by undesirable when using method references? – Joe C Sep 06 '17 at 05:57
  • 1
    Why would using `Foo` instead of the method reference be better than using the method reference? – Holger Sep 06 '17 at 07:25
  • My understanding is that every time a method reference is used, the compiler is actually creating a new anonymous class. Here are a couple posts that outline some performance issues of anonymous classes: https://stackoverflow.com/a/16397738/4234254 https://stackoverflow.com/a/924536/4234254 Essentially, they can be prone to memory leaks, are slower to load, and things like `.equals()` probably won't work as expected. – anqit Sep 06 '17 at 13:12
  • 1
    Your understanding is wrong. Just check the compiled classes. – Holger Sep 06 '17 at 13:15
  • 1
    See [Does a lambda expression create an object on the heap every time it's executed?](https://stackoverflow.com/q/27524445/2711488) and [How will Java lambda functions be compiled?](https://stackoverflow.com/q/16827262/2711488)… – Holger Sep 06 '17 at 13:22

0 Answers0