Reputation:
So I am trying to create a program that helps me keep track of my expenses and i have a question to do with how I create my objects.
So far i have been creating my objects like so:
Grocery milk = new Grocery();
milk.setName("Milk");
milk.setCost(2.84);
milk.setDate(30, 12, 2014);
milk.setType("Food");
My grocery class extends this expense class:
public Expense(){}
public Expense(String name, Double cost, Calendar purchaseDate){
name = _name;
cost = _cost;
purchaseDate = _purchaseDate;
}
So far my grocery class only adds another string parameter that i call type, and so here is my question:
Instead of using set methods to set my paramters for each new created object i would like to do it like this:
Grocery milk = new Grocery("Milk", 2.84, ??Date??, "Food")
But the date parameter is a little more complicated than the other parameters that are just of type string and double, is there a way to do what I want or am i better off using the set methods?
Thanks in advance for any help.
Upvotes: 1
Views: 288
Reputation: 12972
You can simply use an Object
of type Date
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse("16/01/2015");
Grocery milk = new Grocery("Milk", 2.84, date, "Food")
Alternatives include using a Calendar
object (which has more flexible/powerful date manipulation methods), or just storing your date as a String
.
As for deciding whether you should use setX()
methods or using a comprehensive constructor, unless there is a reason not to you can just have both available, and just use the most suitable at any one time.
Further reading:
Upvotes: 4