tin_tin
tin_tin

Reputation: 488

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??

Upvotes: 0

Views: 463

Answers (3)

Jigar Joshi
Jigar Joshi

Reputation: 240860

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

Upvotes: 1

josefx
josefx

Reputation: 15656

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.

Upvotes: 0

Nikolay Antipov
Nikolay Antipov

Reputation: 920

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.

Upvotes: 0

Related Questions