Java Class Constructor Parameters with range limits

I'm new to Java and I'm asking this question just to help me better understand OOP.

Let's say I'm defining a new Class called Hour. To instantiate this Class, we need to specify an integer to indicate the hour of this instance.

Hour hr = new Hour(16); // this means to define an hour that indicates 4pm.

Open in new window


So when we define the Hour Class here, the parameter for the constructor should within the range [0, 24). How can we define such a parameter and can I throw an error when a parameter that is out of this range is specified?

Thanks.
thomaszhwangAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

krakatoaCommented:
Yes, you could do that. Just qualify your constructor with the fact that it throws an Exception, and if the call is outside the bounds, then the new Hour will not get instantiated.

class Hour {

public Hour(int hour) throws Exception{

if(hour<0||hour>24){throw new Exception();}

}

}

Open in new window


called with

class MakeHour{

public static void main(String[] args) throws Exception{System.out.println(new Hour(22));}

}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ksivananthCommented:
>>Just qualify your constructor with the fact that it throws an Exception

IMO, it should throw a RuntimeException not a checked Exception, for instance InvalidArgumentException would be nice fit here!
0
krakatoaCommented:
Sure. Except it would be an IllegalArgumentException. ;) However, I believed that this would constitute a checked exception, as it's not really a bug in the programme logic as such.
0
thomaszhwangAuthor Commented:
Thanks.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.