简体   繁体   English

Java中的匿名子类方法

[英]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. 这部分工作正常,它允许我创建item子类。

However, when attempting to access this method, 但是,当尝试访问此方法时,

NECRONOMICON.getStr()

I get The method getStr() is undefined for the type Item 我得到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. getStr()方法将不可见,因为您正在创建“ Item”的匿名子类。.仅“ Item”及其父类的方法可见。

In other words, when you create an object like 'new Item(){}' you are actually creating a subclass of class Item. 换句话说,当您创建类似“ new Item(){}”的对象时,实际上是在创建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()' 发生这种情况是因为引用变量的类型为'Item',并且类型'Item'不包含名为'getStr()'的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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