Skip to content
Advertisement

Accessing array attributes from other classes with setter/getter

I’m new to Java and was wondering how to access attributes from other classes with setter/getter if they are arrays.

Currently, I have one date class that sets a date with parameters for month/day/year. I need to make another class that uses the date class to set a date of hire to store as an attribute, alongside others.

My code currently looks like this:

public class DateClass {
    
    private int month;
    private int day;
    private int year;

    // MONTH
    public int getMonth() {
        return month;
    }
    
    public void setMonth(int month) {
        this.month = month;
    }
    
    // DAY
    public int getDay() {
        return day;
    }
    
    public void setDay(int day) {
        this.day = day;
    }
    
    // YEAR
    public int getYear() {
        return year;
    }
    
    public void setYear(int year) {
        this.year = year;
    }
    
    // FULL DATE
    public void setDate(int month, int day, int year) {
        setMonth(month);
        setDay(day);
        setYear(year);
    }
    
    public int[] getDate() {
        return new int[] { month, day, year };
        
    }

}

This is the second class:

public class EmployeeClass {

private int[] dateOfHire;

public void setDateOfHire(int[] dateOfHire) {
    dateOfHire.setDate(dateOfHire);
}

public String[] getDateOfHire() {
    return dateOfHire.getDate(dateOfHire);
}

}

The error says: Cannot invoke setDate(int[]) on the array type int[]

How can I fix this? Thanks!

Advertisement

Answer

You will need to create a DateClass object to use its methods. Consider changing your EmployeeClass like so:

public class EmployeeClass {
    
private int[] dateOfHire; // not sure of the purpose of this array
private DateClass dateClassObject; // your variable name is up to you


public EmployeeClass () { // Constructor for this class

    dateClassObject = new DateClass(); // created a new DateClass in the constructor

}

public void setDateOfHire(int[] dateOfHire) {
        // this dateOfHire array is the array that is passed in when
        // method is called. Do not confuse it the array declared as a property.
        int day = dateOfHire[0] // assuming the day is in index 0 of the array
        int month = dateOfHire[1] // assuming the month is in index 1 of the array
        int year = dateOfHire[2] // assuming the year is in index 2 of the array
        dateClassObject.setDate(month, day, year);  // changed to dateClassObject. Also changed setDate to pass correct parameters
    }
    
public int[] getDateOfHire() { // changed String[] to int[] because returned value of getDate() is a int array.
        return dateClassObject.getDate(); // changed to dateClassObject. Removed the parameter.
}
    
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement