匿名内部类

发布于 2024-10-20 00:10:02 字数 358 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小傻瓜 2024-10-27 00:10:02

您正在创建

new Two(),因此类路径中必须有一个有效的类。

使其工作

class Two{

}

class One {
Two two() {
    return new Two() {
//        Two(){}
//        Two(String s) {
//            System.out.println("s= "+s);
//        }//you can't override constuctors
    };
    }
}

或在 new 的左侧必须有超类或接口才能使其工作

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

苍暮颜 2024-10-27 00:10:02
new Two() {
    Two(){}
    Two(String s) {
        System.out.println("s= "+s);
    }
};

匿名内部类之所以称为匿名,是因为它没有自己的名称,必须通过它扩展/实现的基类或接口的名称来引用。

在您的示例中,您创建了 Two 的匿名子类,因此必须将 Two 声明为类或接口。如果类 Two 已声明,则您的类路径中没有它,或者忘记导入它。

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.

丶情人眼里出诗心の 2024-10-27 00:10:02

您没有声明 Two 类。您声明了类 One 和私有成员 two,其中 two 是您尝试初始化的 Two 类的对象匿名建设。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文