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);
	  }
	   
  }

Dani AI

Generated

Yes, you can use conditionals in a constructor; just ensure the class invariants are either fully established or the constructor throws. In Java, constructors are not regular methods; they are special routines that initialize an object. For invalid arguments, prefer throwing unchecked exceptions like IllegalArgumentException or NullPointerException (not a generic Exception) so callers immediately see misuse. For reference parameters, use Objects.requireNonNull, and avoid calling mutating setters from inside constructors; validate first, then assign to fields (ideally final) to avoid partially constructed state. See the Oracle docs on constructors (link), IllegalArgumentException (link), and Objects.requireNonNull (link).

For time validation, consider java.time. It gives clearer, bug-resistant checks for ranges and ordering:

import java.time.LocalTime;

public final class CTime {
  private final LocalTime start;
  private final LocalTime end;

  public CTime(int h1, int m1, int h2, int m2) {
    LocalTime s = LocalTime.of(h1, m1); // throws if out of range
    LocalTime e = LocalTime.of(h2, m2);

    if (s.isBefore(LocalTime.of(7, 0)) ||
        !e.isBefore(LocalTime.of(17, 0)) ||
        !e.isAfter(s)) {
      throw new IllegalArgumentException("Start >= 07:00, end < 17:00, and end after start.");
    }
    this.start = s;
    this.end = e;
  }
}

For mixed types like int and String, validate primitives explicitly (e.g., age > 0) and require non-null references: this.name = Objects.requireNonNull(name, "name");. The java.time API is documented here: link.

Recommended Answers

All 9 Replies

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

Constructor is a method.You can have if statement in a constructor

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

obj people(age,name,gender)

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.

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

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.

Thanks,could you give example with code how to do that

public Person(int age) throws Exception {
  if (age <= 0) throw new Exception("Age must be positive");
  this.age = age;
  (etc)
}

I am asking for solution of this program please.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.