匿名内部类
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());
}
}
上面的示例代码无法编译。它显示“两个无法解析”。 这段代码有什么问题?
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??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在创建
new Two()
,因此类路径中必须有一个有效的类。使其工作
或在 new 的左侧必须有超类或接口才能使其工作
you are creating
new Two()
so there must be a valid class in classpath.make it
or on left side of new there must be super class or interface to make it working
匿名内部类之所以称为匿名,是因为它没有自己的名称,必须通过它扩展/实现的基类或接口的名称来引用。
在您的示例中,您创建了
Two
的匿名子类,因此必须将Two
声明为类或接口。如果类 Two 已声明,则您的类路径中没有它,或者忘记导入它。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
soTwo
has to be declared somewhere either as a class or interface. If the class Two is already declared you either don't have it on your classpath or forgot to import it.您没有声明
Two
类。您声明了类One
和私有成员two
,其中two
是您尝试初始化的Two
类的对象匿名建设。You didn't declare the
Two
class. You declared classOne
and private membertwo
, wheretwo
is object ofTwo
class which you tried to initialize by anonymous construction.