Results 1 to 5 of 5
Thread: please help me
- 03-28-2010, 11:36 PM #1
Member
- Join Date
- Mar 2010
- Posts
- 49
- Rep Power
- 0
please help me
i have this constructor,, if i want to restrict it to create objects if idNum < 8 digits howw ??? do not use exceptions please
Java Code:public Payk(String checkNum, String id ) { this.id = id; //--> how to make it to not accept less than 8 digits this.checkNum = checkNum; }Last edited by javanew; 03-29-2010 at 12:38 AM.
- 03-29-2010, 12:25 AM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
You can check if a number has fewer than 8 digits with:
Java Code:if(num < 10000000 && num > -10000000) { // whatever }
If you don't throw an exception then invoking the Paycheck constructor will return a reference to a newly constructed object, regardless of the arguments and what you do with them.
- 03-29-2010, 12:32 AM #3
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
I've just noticed that idNum is a String. You can get the length of the string easily with the .length() method.
(You may have a problem now that idNum is not a valid integer so the length of the string may not make sense interpreted as a number of digits. And again if there is a restriction on whether an object gets created then the caller must deal with this: either have the constructor throw an exception that the caller does something with, or have the caller check the condition before calling the constructor.)
-
I'm thinking that Exceptions are the best solution here. One kludge though could be to give the class a default ID String, or truncate a too-long string or pad a too-short String, but I don't like these "solutions" at all.
- 03-29-2010, 04:40 AM #5
You need to use the Factory pattern. A factory is a class that produces instances of another class. The factory can be implemented using static methods, a singleton, or you can instantiate multiple factories. The static method approach is the most simple, especially if you simply add a static method to the existing class.
Add a public static method, such as
Change the constructor from public to private, to keep others from using it.Java Code:public static Payk createPayk(final String checkNum, final String id) {}
In the static method, validate the parameters. If they are not valid, return null. Otherwise, call the constructor and return the result.The Java Tutorial. Read it.


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks