为什么不在Anonymous类中的构造函数在java?它矛盾的OOPs规则 [英] Why not Constructor in Anonymous class in java?Its contradicting OOPs rule
问题描述
oops规则是没有类可以存在没有构造函数.its ok.But在java中匿名类不能有其构造函数,因为它没有任何名称。请帮助
The oops rule is "No class can exist without constructor".its ok.But in java Anonymous class can'never have its constructor.because it does not have any name. So it is contradict OOPS rule..I m really confused.Is it breaking OOPS rule?Please help
推荐答案
实际上,他们有一个隐式构造函数。假设您有:
Actually, they have one implicit constructor. Suppose you have:
class A {
A (B b, C b) {
//constructor code
}
}
所以当你创建一个匿名子类A通过 new A(b,c){...}
,它有一个隐式构造函数,其中body super(b,c)
。匿名类不能有自己的显式coustructor的原因,我想,是java命名约定,构造函数名称必须匹配类名称。假设匿名类没有名称,因此你不能为它指定构造函数。
so when you create an anonymous subclass of A via new A(b,c) {...}
, it has one implicit constructor with body super(b,c)
. The reason that anonymous classes can't have their own explicit coustructors, I guess, is java naming convention that constructor names must match the class name. Provided that anonymous class has no name, thus you can't specify constructor for it.
这篇关于为什么不在Anonymous类中的构造函数在java?它矛盾的OOPs规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!