Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How does this program work?

 
Sky Wallen
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I'm just confused on why this program even runs. I understand that the main() section is what runs the program, but in that part, it looks like I just created an object called "noob". Does java automatically run each object that is created.

Also, I am confused on the bolded red section of the program (Line 5). What does that line do? Is that a method? Why do I even need to include that there?

Please help! Thanks in advance!
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64623
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code you pointed out is a constructor. It executes when a new instance of the class is created. So its execution is triggered in this case by instantiating the object in main().
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You create a new Salutation object in the main method, in line 17.

When you create a new object, a constructor is executed to initialize the object.

Lines 5 to 14 are the constructor of the Salutation class.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sky Wallen wrote:
I'm just confused on why this program even runs. I understand that the main() section is what runs the program, but in that part, it looks like I just created an object called "noob".


You created an object. It doesn't have a name. Objects don't have names. You have a variable, which is named "noob", and you set that variable to refer to that object.

Does java automatically run each object that is created.


No. There's no such thing as "running an object." You're executing the constructor you told it to run when you created the object.

Also, I am confused on the bolded red section of the program (Line 5). What does that line do? Is that a method? Why do I even need to include that there?


That code is the declaration of a cosntructor for your Salutaion class. A constructor's job is to put a newly created object into a valid initial state. So when you do new Salutation(), the new operator creates an object, the identifier "Salutation" says that it will be of class Salutation, and the argument list in the parens tell Java which constructor to run. Since you provided empty parens, it says to run the constructor that takes no args--in this case, the one you declared on line 5, and the body of which continues until you close it on line 14.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic