• Post Reply Bookmark Topic Watch Topic
  • New Topic

This program works but I don't know why...is it recurrsion?  RSS feed

 
David Ausman
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just started studying this book called Head First Java, which is really good, and I'm doing one of the exercises. It works but I don't understand why it works. It looks like the class created is making an object of itself inside the main method. How can that be? Can somebody explain the concept to me? See code below. So far, in most of the exercises I have always created a little test driver program with a main method to create objects from another class but this program does it all inside of itself. Confusing. :?:

 
Sunil Kumar
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is perfectly legal to create an object of a class in that class itself. Moreover main is a static method and you cannot use "this" to refer any non static variable or method, hence you need an instance of the class
 
Monu Tripathi
Rancher
Posts: 1369
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi David... Welcome to Javaranch!

The code listed above is perfectly legal.

To use a class, that is, to acess its exposed(externally visible) data members and functions you have to instantiate the class first, unless of course the datamember or the function is declared static (which can be accessed without without instantiation using <classname.propertyname> syntax). Your application(the algorithm embodied in the main method) intends to invoke the go method of the XCopy class, so you are first instantiating the class and then invoking the function on that instance.

There is no recursion here. The main method, which is the entry point for your program, just happens to be in the XCopy class and probably that creates an illusion of "recursion".

I hope this helps.
 
David Ausman
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah, thanks to both of you. That helps a lot and clarifies a basic concept for me before I move on to the next chapter. This Java thing is really fun. It's hard to put the book down and go to sleep.
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

And no.... it is not recursion.

Henry
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!