0

Is it OK to have if statement in the constructor
Thanks

public class CTime {
  private int start_hour;
  private int end_hour;
  private int start_minute;
  private int end_minute;
  public CTime(int h1,int m1,int h2,int m2){
	  if(h1>=7 && h2<17 && h2*60+m2>h1*60+m1){
	  setStartHour(h1);
	  setStartMinute(m1);
	  setEndHour(h2);
	  setEndMinute(m2);
	  }
	   
  }
3
Contributors
8
Replies
10
Views
6 Years
Discussion Span
Last Post by JamesCherrill
0

Yes. Just make sure that the new Object is has all its variables in a decent state regardless of which conditional paths are executed.

0

Thanks ,another question is there method witch is checking if the object arguments are different then null.

obj people(age,name,gender)

0

Do you mean like

if (age != null) ...

but you can only do this for reference types (objects), things like ints or floats can't be null anyway.

0

Thanks,I meant to check int!=0 && String!=null
in the same object

0

Yes, you can do exactly that.
The more interesting question is what will you do if you find invalid parameters in a constructor? How will the calling method know that its new Person(0, "Who?", 'X'); statement wasn't executed as it expected?
One option is to declare the constructor as throws (some kind of exception) and throw a new Exception if the params are invalid.

1
public Person(int age) throws Exception {
  if (age <= 0) throw new Exception("Age must be positive");
  this.age = age;
  (etc)
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.