简体   繁体   English

匿名内班

[英]Anonymous Inner class

class One {
Two two() {
    return new Two() {
        Two(){}
        Two(String s) {
            System.out.println("s= "+s);
        }
    };
    }
}

class Ajay {
    public static void main(String ...strings ){
        One one=new One();
        System.out.println(one.two());
    }
}

The above sample code cannot be compiled.It says "Two cannot be resolved". 上面的示例代码无法编译。它说“两个无法解析”。 What is the problem in this code?? 这段代码有什么问题??

you are creating 你正在创造

new Two() so there must be a valid class in classpath. new Two()因此在classpath中必须有一个有效的类。

make it 做了

class Two{

}

class One {
Two two() {
    return new Two() {
//        Two(){}
//        Two(String s) {
//            System.out.println("s= "+s);
//        }//you can't override constuctors
    };
    }
}

or on left side of new there must be super class or interface to make it working 或在new的左侧必须有超类或接口才能使其正常工作

You didn't declare the Two class. 您没有声明Two类。 You declared class One and private member two , where two is object of Two class which you tried to initialize by anonymous construction. 您声明了类One和私有成员two ,其中two是您试图通过匿名构造初始化的Two类的对象。

new Two() {
    Two(){}
    Two(String s) {
        System.out.println("s= "+s);
    }
};

An anonymous inner class is called anonymous because it doesn't have its own name and has to be referred to by the name of the base-class or interface it extends/implements. 匿名内部类称为匿名,因为它没有自己的名称,必须由其扩展/实现的基类或接口的名称引用。

In your example you create an anonymous subclass of Two so Two has to be declared somewhere either as a class or interface. 在您的示例中,您创建了一个Two的匿名子类,因此必须在某个地方将Two声明为类或接口。 If the class Two is already declared you either don't have it on your classpath or forgot to import it. 如果已经声明了类Two,那么您要么在类路径中没有它,要么忘记导入它。

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

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