Roopali Neeraj
Roopali Neeraj

Reputation: 53

Create an object without using a class in Java

I was asked this question in an interview and I could not find any direct answer to it online.

"Can you create an object in Java without using a class?"

There is no context or addition to this question, so please do not label this question as incomplete or pointless. If this question is a trick one or needs context, let me know.

Upvotes: 2

Views: 191

Answers (2)

MC Emperor
MC Emperor

Reputation: 22977

Well, the answer of Joni is a very good one. I did not immediately think of that.

However, there is no way for you to instantiate an object without being in the context if a class.

A soon as you have written something like new int[0], you have already written class MyClass { or something like that. The new keyword is never valid outside the definition of a class.

So the actual answer is no.


So is this a trick question? Yes, absolutely. Is this a clear question? Not really. The answer may as well depend on what exactly is meant by the word "using". I would ask for clarity first.

Upvotes: 2

Joni
Joni

Reputation: 111239

Yes: arrays are objects, but there are no array classes.

The Java language and JVM specifications make a distinction between class instances and arrays in many places. Most notably:

JLS 4.3.1:

An object is a class instance or an array.

JLS 4.3.2:

All class and array types inherit (§8.4.8) the methods of class Object

JVM 3.9

Java Virtual Machine arrays are also objects.

(After a section that was dedicated to objects that are class instances)

Upvotes: 6

Related Questions