Passing constructor parameters to initialize an object [duplicate] - java

This question already has answers here:
How to initialize a reference attribute in a constructor in Java?
(3 answers)
Closed 7 years ago.
I'm writing a java class that borrows elements of another class and need to pass three of the four parameters of the constructor to initialize the other class object. I'm lost as to how to initialize it, though. Any help is much appreciated. Here's what I have right now:
private String name;
private MyDate birthday;
/**
* Constructs a new Person object.
*/
public Person(String name, int month, int day, int year) {
this.birthday = birthday(month, day, year);
this.name = name;
}

This will depend on whether or not the birthday class is connected by some means (extended or friended) or if the birthday.birthday field is publicly accessible.
For example, if you wanted to keep up with good practice. You could set up a
GetBirthday(); method inside of the birthday class and do the following.
private MyDate birthdate;
public Person(String name, int month, int day, int year) {
birthday bDay = new birthday(month, day, year);
this.birthdate = bDay.GetBirthday();
this.name = name;
}
You could also create an inline function birthday() which calculates birthdays, but I would not advise doing it as such.

Related

Java OOP - How to get year in DOB and current year then calculate age?

I have three classes. My driver class, a Person class, and a Chore class.
I have chores and family members listed in two separate csv files.
The family members file just contains names and dob's (01/01/1901).
So the first thing I want to do is calculate each family member's age based on the year in their dob and get the current year then get the difference of the two. How do I select for just the year in each person's dob and how do I get the current year?
public int currentAge(LocalDate dob, LocalDate currentDate){
if ((dob != null) && (currentDate != null)) {
return Period.between(dob, currentDate).getYears();
} else {
return 0;
}
}
public int getCurrentAge(){
return currentAge;
}
To calculate the age of a person from their birthdate, using Java 8+ Time API, use this method:
public static int getAge(LocalDate dob) {
LocalDate today = LocalDate.now();
int age = today.getYear() - dob.getYear();
if (MonthDay.from(today).isBefore(MonthDay.from(dob)))
age--; // before birthday in current year
return age;
}
Java 8 compatible solution :
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
public class Demo
{
public static void main(String[] args)
{
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy");
String date = "16/08/2016";
LocalDate dob = LocalDate.parse(date, formatter);
System.out.println(daysBetween(dob));
}
private static long daysBetween(LocalDate dob)
{
return Period
.between(dob,
LocalDate.now())
.getYears();
}
}
We can add a data member in the People for holding the chore information.
class People{
private final String name;
private final LocalDate dob;
private final String gender;
private List<Chores> choresList;
}
You can use the following method or something similar to get the age:
private long daysBetween(Date one, Date two) {
long difference = (one.getTime()-two.getTime())/86400000;
return Math.abs(difference);
}
Read more here or here.

I can't seem to figure out how to print the values I've assigned to my objects [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 2 years ago.
This might be an easy answer but I'm new and my professor hasn't been much help, also feel free to correct my terminology. Essentially I have a class "Employee" and I'm trying to add several instances of it to an ArrayList to be printed later in Main. It looks kind of like this:
public Employee(int id, String name, String bday, String gender, String job, int org)
{
this.id = id;
this.name = name;
this.bday = bday;
this.gender = gender;
this.job = job;
this.org = org;
}
All I really need to know how to do is print the values I've managed to assign to the constructor i.e. when I call a specific object from the ArrayList I'll be able to print the object's specific id, name, etc. I figured out that I can do it by creating a method for each individual variable but that would be really messy and inefficient, I'm looking for one method to call that would be able to do this.
Override Object.toString() in Employee. Something like,
#Override
public String toString() {
return String.format("Employee id=%d, name=%s, bday=%s, gender=%s, job=%s, org=%s",
id, name, bday, gender, job, org);
}
Then whenever you try and print it, the toString of Employee will be invoked.
System.out.println(new Employee(1, "Test", "A Birthday",
"Yes", "Something", "Somewhere"));

How to pass a value from a constructor to a setter in another class in JAVA?

Im learning object oriented programming in school right now, and there are some aspects of it I don't quite understand yet. I have a program that creates a database of users with their names, and birthdates. So I have 3 classes: person, PersonProgram(the main), and Date. The Person class has the constructor, setter, and getters for the names and the birth date. The Date class has error checking for proper dates and leap years etc. In the main program I create 5 People, and then give menu options to change and modify the names and dates. So for example, if the user wants to change the name my code looks like this:
System.out.println("Enter new first name:");
people[choice-1].setFirstName(input.next());
and that works and makes sense to me. But I want to know how I can change the date properly? The Date constructor takes 3 integers for the day, year, and month, so in the main program I prompt the user to input the 3 new dateswhich are stored in day, month, year integers. So my understanding is from there I would pass those 3 integers to the Date constructor:
new Date(month, day, year);
What I am confused on is where to go from there. The Date constructor gets the new Date call, and passes it to the setters. How can this newly created date object be passed back to the Person program, so the setter in Person for the birthdate can update the corresponding Person object? If I am not clear on my question please let me know, I figured I could articulate what I am trying to ask without posting all my code.
In your Person class you should have something like this:
public class Person {
private Date birthDate;
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate){
this.birthDate = birthDate;
}
}
And then in you would set the birthDate like:
person[choice-1].setBirthDate(new Date(month,day,year));
Taking into consideration that you are starting with OOP there is an important concept here, Encapsulation, the Person class restricts the free access to its fields, like birthDate, and sets the rules for the interaction with them. As an example you could check if the date is null before assigning it.
public void setBirthDate(Date birthDate){
if(birthDate != null) {
this.birthDate = birthDate;
} else {
//Whatever you wanna do here (throw an Exception, etc, etc)
}
}
Comment Question
Although it would be better to create another question:
Do I have to create an instance of the Date class in my Person class? Or anywhere for that matter?
No, the property/field birthDate is a reference to a Date object which will be stored in memory until no references are left. And it's up to you where to create them, nonetheless there are Creational Patterns, a familiy of Design Patterns that help you with this matter.
is it the birth date in person class of type 'Date'?
if so, you should create an instance of your class Date , do the control that you need and pass it to the constructor or setter of the birth date in the persson instance .
Date birthDate = new Date(month, day, year);
// Some controls
people[choice-1].setBirthDate(birthDate);
Date the_birth_date = new Date(mounth, day, year);
people[choice - 1].setBirthDate(the_birth_date);
You can set it like this: people[choice-1].setBirthday(new Date(month, day, year));. You would have to give the option to select the Person first.

One instance variable for multiple values

I'm a Java beginner so bear with me
The requirements are only one instance variable, one constructor, and one method is allowed. Is it possible to make description(instance variable, not the constructor) store multiple values for a date(such as year, month and day)? Something like the code below. I can print it fine if there are multiple instance variables but not with one.
import java.util.Date;
public class MyDate {
public Date description; //type might be wrong
public MyDate(int year, int month, int day, String description) {
//not sure what to put
}
public String toString() {
//return d + "/" + m + "/" + y + " " + description;
}
}
There are different way to store your value into one variable.
Store your values in key-value pair using Map.
Store values in simple List or Arrays and retrieve using index.
Make one class include all your required attribute as instant member for that class. Create object of that class set value to
instant variable.
May one this way will help to solved your problem.
Sample Example :
1. Using Map<String,Object> :
public Map<String,Object> description; //type might be wrong
public MyDate(int year, int month, int day, String descriptionTxt) {
description = new HashMap<String, Object>();
description.put("year", year);
description.put("month", month);
description.put("day", day);
description.put("desc", descriptionTxt);
}
2.Using List<Object> :
public List<Object> description; //type might be wrong
public MyDate(int year, int month, int day, String descriptionTxt) {
description = new ArrayList<Object>();
description.add(year);
description.add( month);
description.add(day);
description.add(descriptionTxt);
}
3.Using Class :
class MyClass
{
private int year;
private int month;
private int day;
private String desc;
//Getter and Setter Method
}
//MyDate class
public MyClass description; //type might be wrong
public void MyDate(int year, int month, int day, String descriptionTxt) {
description = new MyClass();
description.setYear(year);
description.setMonth(month);
description.setDay(day);
description.setDesc(descriptionTxt);
}

How to initialize a reference attribute in a constructor in Java?

I'm adding an instance variable to a class "Person" which is a reference type ("Date", which I have written a class for). In the constructor for my Person class, I am therefore trying to initialize the Date attribute using the constructor of the Date class, but I am unsure how to do this. Previously I have only ever initialized primitive types (or Strings), as seen below. This is a segment from my code. I'm unsure how to initialize "birthday" so that it uses the constructor of the Date class. Thanks!
public class Person {
/* Attribute declarations */
private String lastName; // last name
private String firstName; // first name
private String email; // email address
private Date birthday; // birth date
/**
* Constructor initializes the person's name, email address, and birthday
*/
public Person(String firstName, String lastName, String email, Date birthday) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.birthday = ????
Are you saying you want to initialize this.birthday in the constructor of Person using the Date constructor? Then use the new keyword like this:
this.birthday = new Date(<arguments if any exist>);
new calls the constructor of an object. If that's the case, you do not need the Date birthday constructor argument for Person, unless you use it for something else.
You can do this:
this.birthday = new Date(birthday.getTime());
This creates a copy of the date object. Since a Date can be modified it is dangerous to use the same object, which you'd be doing if you just copied the reference:
this.birthday = birthday;
That would allow the outside world to change your birthday without you knowing about it.
You can just simple
this.birthday = (Date) birthday.clone();
Why this way instead of ?
this.birthday = birthday;
Cause outsiders can modify your date object, and then they are modifying your internal structure and that is not good, breaks encapsulation.
Why this way instead of ?
this.birthday = new Date(birthday.getTime());
Date is not a final class what happen if Date object you pass is not a "true Date" and is a subclass , if you do this don't preserve internal structure of subclass, but when you cloning preserves the information, but this approach it depends on what you want.

Categories

Resources