问题
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??
回答1:
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. If the class Two is already declared you either don't have it on your classpath or forgot to import it.
回答2:
you are creating
new Two()
so there must be a valid class in 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
回答3:
You didn't declare the Two
class. You declared class One
and private member two
, where two
is object of Two
class which you tried to initialize by anonymous construction.
来源:https://stackoverflow.com/questions/5153221/anonymous-inner-class