During my interview, interviewer asked me
Can we create class without name ?
Since, I was not sure, if it is really possible to create a class without name. So, I said No.
Later, I tried Googling and found, others are also looking for the answer of the same question, but I didn't found clear answer.
I will appreciate, if anyone clearly explain about this class. I mean, what that class technically known as and how can we instantiate this class ?
Raman is right in that all objects inherit the methods of the Object class, so you technically can't have a class without any methods at all.
Explanation: A class without a name will not have a destructor. The object is made so constructor is required but the destructor is not.
Object = new Example() { public void display() { System. out. println("Anonymous class overrides the method display()."); } }; Here, an object of the anonymous class is created dynamically when we need to override the display() method.
We can call a static method by using the ClassName. methodName. The best example of the static method is the main() method. It is called without creating the object.
Yes, it's called an anonymous class/struct.
In C++:
class {
} x;
x
is an object of the type, and you can't create any more, because, well, how would you, given that the class doesn't have a name and all....
how would one call constructor and destructors
You don't. In both Java and C++ constructors and destructors hold the same name as the class (they're not PHP - __construct
or whatever), and the missing name kind of gets in the way.
Its also called an anonymous class in Java.
// create a new instance of an anonymous class.
Serializable s = new Serializable() {
};
Note: In the JVM, all classes have a name, it's generated by the compiler for you.
You can't define constructors, but it can have an instance initializer block which does much the same thing.
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