• Post Reply Bookmark Topic Watch Topic
  • New Topic

A query regarding the given code  RSS feed

 
Rajib Ban
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!
Presently, I am following an old book, "Learn Java in a Weekend" by Joseph Russell, Premier Press, 2002. I have three source codes for building up a calculator.
Does CodeRanch have a copy of the said book?
The program has compiled and is giving the desired result.
But I can't understand why the CalculatorHelper.java initialises an object reference of the Private variable name calcModel of the Type CalculatorModel? Why `Private`? I can understand that the object constructor is a no-argument constructor that simply initializes the CalculatorModel instance.
An object constructor should have had the structure: . Instead, it has a different structure,  first, and then encapsulated as within the
The codes are given below:
(1) CalculatorModel.java


(2) CalculatorHelper.java


(3) CalculatorHelperTest.java
 
Mishra Saurabh
Greenhorn
Posts: 24
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
As far as I get your question, you asked why the calcModel object is instantiated as private.
I have been following the book JAVA The complete Reference, by Herbert Schildt.
I have read it somewhere in that book that it is good practice to not let outer code access any data member of the class directly, accessing data member through public methods is always preferred
This makes sure that the integrity of that data member is not compromised.
Hope it helps. Although I am not that good at answering questions as people in this forum.
Please do tell me if you understood or not.
Thanks
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't use books printed before about 2005; they are too old.
What you are describing is the usual practice of giving fields private access, and initialising them in the constructor. Aren't you familiar with constructors yet?
 
Rajib Ban
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dr. Richie,
I am familiar with Constructors so far as Code (3) CalculatorHelperTest.java, by Line 4, is concerned, as described by the book.
But not familiar with Code (2) CalculatorHelper.java, by Lines 3-6 are concerned.

I procured a book that was accessible to me.
Thank you for your queries. Could you suggest any online book that has the details on everything on Java, including the Constructor methods?
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!