I have this class
class Customer{
int ID;
Time arriveTime;
Time serviceTime;
Time completeTime;
int transaction;
}
Don't I need a constructor in order to set the values inside? I will be using this class to hold different values while making an array of Customers. Wouldn't this mean I would need this in order to set the values?
public Customer(int id, Time arrive, Time service, Time complete, int trans){
ID = id;
arriveTime = arrive;
serviceTime = service;
completeTime = complete;
transaction = trans;
}
I only need the Customer class to hold the information about each customer.
You didn't define a constructor at all, so the default constructor will be added for you. It will, however, not set any of those fields, so you'll have to go:
And so on. A couple of things:
c.ID
but others won't. You might want to declare them publicThe fields can be set from outside the class, meaning you can use another class to set the values.
A constructor however is a more convenient way to do this indeed and can shield manipulations to the fields by another class (implemented by some programmer who might disturb the intended functionality).
In case a class only is implemented to store a record, you can make the fields
private
andfinal
and implement the appropriate getters.The method that you are suggesting does not do a very good job of abstracting and separating variables. It allows them to be messed with by any code at will.
Part of Java is OOP, or Object Oriented Programming. If you make certain parts of the class
private
and separated from the rest of the code, then it will limit access from other code, which helps your class follow the OO principle of encapsulation.Instead, I would make a constructor that fills in the fields when appropriate, such as
arrive
andid
. I would make the variablesprivate
. Also, I would makeid
a static member, because it would be incremented for every new customer.Yes, you need a constructor to assign parameters to your class during object creation, or you could reference each variable individually though the instance and assign it, e.g:
A constructor just makes this easier as you do not need to write more code than necessary.
I do recommend using constructors to assign various values to a class instance instead of doing it manually every time you create an instance of an object.
Not necessarily, as by default your attributes (values) without a visibility modifier can be set directly on instances of Customer from code in the same package.
For example:
More on modifier access levels here.