简体   繁体   中英

Override method - Class variable

let me say first that I did try to Google this, but I'm not really sure what I'm looking for. I understand I could use a setter method, but is there a way to access the fields directly?

List<String> token = new ArrayList<String>();
List<String> lemma = new ArrayList<String>();
List<String> pos   = new ArrayList<String>();

tt.setHandler(new TokenHandler<String>() {
   @Override
   public void token(final String token, final String pos, final String lemma) {
      this.token.add(token); // cannot be resolved or is not a field
      this.lemma.add(lemma); // cannot be resolved or is not a field
      this.pos.add(pos);     // cannot be resolved or is not a field
   }
});

Can you help me?!

Thanks!

Bob

Using the keyword this in front of the variable, indicates that you want to access to instance fields. In this case the fields you would like to access, would belong to the anonymous class instance new TokenHandler<String>() { //... } . Since they are not declared inside the anonymous class, the compiler is not able to resolve them. That's why you are probably getting an error. Add the keyword final and access to the variables without the this -keyword:

final List<String> tokens = new ArrayList<String>();
final List<String> lemmas = new ArrayList<String>();
final List<String> positions   = new ArrayList<String>();

tt.setHandler(new TokenHandler<String>() {
   @Override
   public void token(final String token, final String pos, final String lemma) {
      tokens.add(token); 
      lemmas.add(lemma); 
      positions.add(pos);
   }
});

For further information about why you need final see this question.

EDIT:

Also, be careful with the ambigous names (parameter list vs. method variables).

而不是使用的this.token使用OuterClass.this.token其中OuterClass是你的类的名称

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM