Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private variables/methods in anonymous class?

I have created an anonymous class in which I declare a few variables and methods. My java teacher tells me to make these private. I don't see how changing the modifier makes any difference since these variables and methods are private to the anonymous class anyway, so I prefer to have no modifier at all. Who is right and what makes more sense? See below for example code where I choose no modifier for 'map' and 'convert' rather than making them private.

Collections.sort(list, new Comparator<String>(){
  public int compare(String a, String b){
    return convert(a).compareTo(convert(b));
  }
  Map<String, String> map = new HashMap<String, String>();
  String convert(String s) {
    String u = map.get(s);
    if (u == null)
      map.put(s, u = s.toUpperCase());
    return u;
  }
});
like image 215
John Avatar asked Jan 04 '10 19:01

John


People also ask

Can private variables be used in methods?

No, it is a syntax error, you can not use access modifiers within a method.

Can Anonymous classes be private?

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.

Can anonymous class have multiple methods?

Because the EventHandler<ActionEvent> interface contains only one method, you can use a lambda expression instead of an anonymous class expression. See the section Lambda Expressions for more information. Anonymous classes are ideal for implementing an interface that contains two or more methods.

Can anonymous class have abstract methods?

3.1. The syntax of anonymous classes does not allow us to make them implement multiple interfaces. During construction, there might exist exactly one instance of an anonymous class. Therefore, they can never be abstract. Since they have no name, we can't extend them.


1 Answers

I would be tempted to make them private simply for the fact that if you refactor the code and pull the anonymous class out as a standard class (Intellij, for example, can do this at the click of a button), having private fields is what you really want. You won't have to go and rework your classes to match your standard.

like image 194
Brian Agnew Avatar answered Sep 18 '22 21:09

Brian Agnew