简体   繁体   中英

Anonymous subclass methods in Java

So basically, I have an object, which i initialize and then create an anonymous subclass of:

public NECRONOMICON;

NECRONOMICON = new Item(arguments here){
public ArrayList<String> str = new ArrayList<String>();

public ArrayList<String> getStr(){
    return this.str;
}

That was pseudocode, but hopefully, my intentions are clear. This part works fine, and it allows me to create the item subclass.

However, when attempting to access this method,

NECRONOMICON.getStr()

I get The method getStr() is undefined for the type Item

Any help would be appreciated.

The method getStr() won't be visible because you are creating an anonymous subclass of 'Item'.. only methods of 'Item' and its parent class are visible.

In other words, when you create an object like 'new Item(){}' you are actually creating a subclass of class Item. This new subclass is anonymous, and any new method that you define in it won't be accessible by its reference. This happen because the reference variable is of type 'Item', and type 'Item' doesn't contain a method named 'getStr()'

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