I'm currently writing a basic video loans application, and need help with my Borrower class. The class defines the membership number and borrowing limit, whilst extending the basic capabilities of the person class. The person class simply defines the data for a person, such as name, telephone number etc.
This may be a simple question, but how do I provide a constructor in the Borrower class, that will read data from a line in a text file and create a new Borrower object? I basically need to construct a new Borrower object from a line in a file.
I'm still pretty new to Java, so would really appreciate any help!!
You really don't want to do that. You want to read the data in somewhere else, and then pass the data to a normal constructor. It's bad design for a number of reasons to have the Borrower class do the file reading itself.
Do you need help with the actual reading and parsing of the file?
First, create a constructor with enough information to find and retrieve the specified information, which it seems like you've done all ready.
Next, just write a method that parses and reads the files and uses it in the constructor. I tend to always skim Java Almanac for examples when doing something like this, they have tons of excellent commonly used techniques. For java.io check:
I agree that you don't want the Borrower class to know how to read the file or "parse" a line of text - after all, what happens if the file isn't really intended to be used to construct a Borrower object? The constructor would be a bad place to discover this.
If you need to get information from a text file, and use that to build a Borrower object, you can use a "BorrowerFileReader" class (pick another name if you want). You could pass the location of a text file to a BorrowerFileReader object, have it find the file, open it, read in a line, "parse" it for the items needed to construct a Borrower, and (assuming the file contains what is expected), return a Borrower object. This is a sort of "Factory" (a pattern you may have heard about - or may in the future).
So, do you need help opening and reading the text file, or do you need more information on using another class to read the files and create Borrower objects? Or something else?
Joined: Nov 06, 2005
Thanks for all the help.
This is currently part of an exercise I'm working on, and as such, for better or for worse, I'm required to include the call to the file from the borrower class. I'm not sure I agree with this way, but I don't really have a choice.
I've tried to implement the constructor as follows,
The borrower class now looks as following,
Do you think this will work and achieve what is required?