Why does adding a public field to an anonymous class in Java not work?

后端 未结 8 1598
渐次进展
渐次进展 2020-12-17 15:48

I have an example class defined like below:

public class FooBar {

  void method1(Foo foo){ // Should be overwritten
    ...
  }

}

Later,

8条回答
  •  天命终不由人
    2020-12-17 16:44

    Because the type of the variable "fooBar" is FooBar (the run-time type of the object in said variable is that of the anonymous class implementing FooBar which is also a subtype of FooBar)...

    ...and the type FooBar does not have said member. Hence, a compile error. (Remember, the variable "fooBar" can contain any object conforming to FooBar, even those without name, and thus the compiler rejects the code which is not type-safe.)

    Edit: For one solution, see irreputable's answer which uses a Local Class Declaration to create a new named type (to replace the anonymous type in the post).

    Java does not support a way to do this (mainly: Java does not support useful type inference), although the following does work, even if not very useful:

    (new foobar(){
      public String name = null;
      @Override
      void method1(Foo foo){
        ...
      }
    }).name = "fred";
    

    Happy coding.


    Both Scala and C# support the required type inference, and thus anonymous type specializations, of local variables. (Although C# does not support extending existing types anonymously). Java, however, does not.

提交回复
热议问题