Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not Constructor in Anonymous class in java?Its contradicting OOPs rule [closed]

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

like image 735
Hardeep Singh Avatar asked Dec 19 '22 18:12

Hardeep Singh


2 Answers

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.

like image 162
Alexander Tokarev Avatar answered Feb 23 '23 00:02

Alexander Tokarev


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.

like image 37
Mike Samuel Avatar answered Feb 23 '23 01:02

Mike Samuel