Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

People also ask

Can fields be public in Java?

If you have a Class object, you can obtain its public fields (including inherited fields) by calling getFields() on the Class object.

Can Anonymous classes be private?

3.12. An anonymous class cannot define any static fields, methods, or classes, except for staticfinal constants. Interfaces cannot be defined anonymously, since there is no way to implement an interface without a name. Also, like local classes, anonymous classes cannot be public, private, protected, or static.

What is true about anonymous class in Java?

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. 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.

Are anonymous objects possible in Java?

Anonymous object in Java means creating an object without any reference variable. Generally, when creating an object in Java, you need to assign a name to the object. But the anonymous object in Java allows you to create an object without any name assigned to that object.


I have an example class defined like below:

public class FooBar {

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

}

Later, when I try this:

FooBar fooBar = new FooBar(){
  public String name = null;
  @Override
  void method1(Foo foo){
    ...
  }
};

fooBar.name = "Test";

I get an error saying that the name field does not exist. Why?