Anonymous Inner class

508 Views Asked by At
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??

3

There are 3 best solutions below

1
josefx On BEST ANSWER
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.

3
Jigar Joshi On

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

2
Nikolay Antipov On

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.