• Post Reply Bookmark Topic Watch Topic
  • New Topic

Defining Classes  RSS feed

 
rajeev ramachandran
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I have some experience of C, but am trying to teach myself OO and Java from "Head First Java". I do have a question
In Chapter 3 (page 63 of the edition I have), the statement
'Hobbits[] h = new Hobbits[3]' occurs within the Hobbit class. And on page 66, 'HeapQuiz [] hq= new HeapQuiz()' occurs within the HeapQuiz class.
Is it possible to create objects and arrays of objects within the definition of the class that defines that object?
Thanks and Regards
Rajeev
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

We have a strict policy on display names, which must be a real first and last name with a space between.

Please go here and fix your display name up, pronto. Thanks, pardner!

To answer your question: yes. You do have to be careful to avoid recursion. If a class has a member variable that's an instance of its own class, then it shouldn't be initialized to a new instance in the class's constructor or class body!
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16059
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Chapter 3 (page 63 of the edition I have), the statement
'Hobbits[] h = new Hobbits[3]' occurs within the Hobbit class. And on page 66, 'HeapQuiz [] hq= new HeapQuiz()' occurs within the HeapQuiz class.


That second line looks like a mistake. The variable 'hq' is an array of HeapQuiz objects, and you can't assign a single HeapQuiz object to that variable.

Is it possible to create objects and arrays of objects within the definition of the class that defines that object?


Yes.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!