简体   繁体   中英

Use an instance inside an anonymous class

I tried to use an instance of a anonymous class inside it when it's defined, but there were multiple errors given by IDE. I commented the question below. Is it a completely wrong way of using anonymous class, or is this because I wrote something incorrect? Thanks in advance!

  zoo = new ArrayList <AbstractCat>();
  AbstractCat cat = new AbstractCat (){//trying to create an anonymous class and add the instance cat to the ArrayList 
          zoo.add(this); //this line has multiple errors, I tried add(cat) but didn't work
          .....
          // override the methods in AbstractCat

If I read your question in a different manner, it seems that you're trying to take the instance of AbstractCat that you've created, and add it to your zoo list.

Well...you can't do it in the manner you're attempting to from within the anonymous class. You might be able to, but I'd strongly discourage it.

Instead, it'd be simpler for you to place the instance of the anonymous class that you hold into the list instead.

AbstractCat cat = new AbstractCat() {
    // impl
}

zoo.add(cat);

您不会这样做,您需要在定义匿名类之后执行zoo.add(cat)

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