简体   繁体   English

Java中的匿名内部类不起作用。 为什么?

[英]Anonymous Inner Class in Java not working. Why?

The class in question is this. 有问题的班级是这个。 As you can see, it's very simple. 如您所见,这非常简单。 Just to learn about the workings of anonymous inner classes. 只是为了了解匿名内部类的工作原理。 In this case I am getting 4 errors saying that the symbols WaterLevel and ChlorineLevel cannot be found. 在这种情况下,我收到4条错误消息,提示找不到WaterLevel和ChlorineLevel符号。 Can you see what is wrong with this? 您能知道这有什么问题吗?

public class Pool {
    public WaterLevel level() {
        return new WaterLevel() {
            private String level = "empty";
            public String litresToFull() { return "3000"; }
        };
    }

    public ChlorineLevel chlorine(final int amt){
        return new ChlorineLevel() {
            private int level = amt;
            int addChlorine() { level += amt; return level; }
        };
    }
}

Rohit Jain said 罗希特·贾恩(Rohit Jain)说

True, but those anonymous inner classes are actually subclass of WaterLevel and ChlorineLevel respectively. 是的,但是那些匿名内部类实际上分别是WaterLevel和ChlorineLevel的子类。 You've to have those classes. 您必须拥有这些课程。

This lead to me to realize that I have to define an interface for each anonymous inner class that I'm using. 这使我意识到,我必须为我使用的每个匿名内部类定义一个接口。 Just wanted to post this so that it's obvious this is solved. 只是想发布此内容,以便很明显地解决了该问题。

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

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