Search code examples
javaclassobjectconstructornew-operator

In Java, Is it possible to create an object without a class and a constructor?


there!

I'm new on Java and I recently stumbled upon constructors concept. I think that I understood the concept, but the book that I'm reading introduced the concept of objects in arrays and I got lost.

In the examples, the book simply creates an object using the constructor new. But the problem is that the book uses it with an object reference variable that refers to an object in a nonexistent class.

Let me write it in code.

Dog [] pets;

pets = new Dog[];

I understand that an object called Dog that contains arrays [] was created.

When, in my current understanding it should be like this:

//We have a class named Dog

public class Dog{

//And We have a basic default constructor here
    public Dog(){
    }

}

//We have another class

public Class2{

//In this class we create a "reference variable" 
//to create an object from the above class named Dog.


Dog[] pets;
pets= new Dog[];

}

So, I don't know if the book simply obviated the class named Dog or if it's possible to create an object Dog[] on demand, without having a class/constructor to call.

I'd appreciate if somebody could clarify this concepts to me.

Thanks for reading!


Solution

  • The declaration Dog[] pets; requires there to be a class or interface named Dog. It declares the variable pets with type Dog[], meaning that pets will always hold either null or a reference to an array of type Dog[] (or perhaps a subtype such as Chihuahua[]). Your book is apparently assuming that Dog is defined elsewhere, and letting you fill in the blanks. (This is very normal: books don't usually present whole programs for every example, because they don't want to distract from the specific thing they're showing you.)

    The assignment pets = new Dog[] isn't valid: you can't create an array without saying how many elements it has, either with a number (new Dog[3]) or by explicitly listing elements (new Dog[] { null, null, null }).

    The assignment pets = new Dog[3] requires there to be a class or interface named Dog, but it does not call any of Dog's constructors (because it doesn't create a Dog, only a Dog[]), so it doesn't care whether Dog has a no-arg constructor, whether Dog is a concrete class, whether any of Dog's constructors are accessible, or anything like that.