Anonymous Inner class

浪尽此生 提交于 2020-01-01 21:38:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!