I have this class
class Customer{
int ID;
Time arriveTime;
Time serviceTime;
Time completeTime;
int transaction;
}
Don\'t I
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
and id
. I would make the variables private
. Also, I would make id
a static member, because it would be incremented for every new 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:
Customer c = new Customer();
c.ID = 34
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
and final
and implement the appropriate getters.
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:
Customer c = new Customer(); // default constructor
c.ID = 5;
... (etc.)
More on modifier access levels here.
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:
Customer c = new Customer();
c.id = 0;
// etc
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.