Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interview : Is it possible to create a class without name?

Tags:

java

c++

oop

class

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 ?

like image 549
Ravi Avatar asked Oct 22 '12 14:10

Ravi


People also ask

Is it possible to create a class without member methods at all?

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.

What if a class doesn't have a name?

Explanation: A class without a name will not have a destructor. The object is made so constructor is required but the destructor is not.

How do you make an anonymous class in Java?

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.

How do you call a class method without creating the object of the class?

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.


2 Answers

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.

like image 111
Luchian Grigore Avatar answered Oct 27 '22 12:10

Luchian Grigore


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.

like image 45
Peter Lawrey Avatar answered Oct 27 '22 14:10

Peter Lawrey