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
}
}
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.
In the anonymous class
Foo foo = new Foo(x) {};
the (x)
specifies the actual parameters passed to the super-class constructor.
The whole anonymous class syntax is syntactic-sugar, an abbreviated syntax that the compiler translates into more basic syntactic structures.
So anonymous classes are not really anonymous. The example class above is assigned an auto-generated name like Foo$1
and it has an implied constructor of the form
Foo$1(T x) { super(x); }
where T is taken from the most-specific super-class constructor whose signature can accept the arguments (x)
based on Java's normal rules for choosing among overridden signatures based on static types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With