Advertisement Jump to content
Sign in to follow this  
Keyeszx

Arrays of class objects in Java

This topic is 1782 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

For a class assignment we've been tasked with making an appointment class that holds some variables and another class that makes an array of the appointment class. But I'm not sure if I'm adding the appointment object correctly.

    public class Appointment {
     
        private int date, hour, minute;
        private String month, msg;
     
        public Appointment() {
            setMonth("APR");
            setDate(4);
            setHour(0);
            setMinute(0);
            setMessage("Default Message");
        }
    //constructor that takes parameters
    //main method that creates two objects to test the constructors, will be deleted before finished
    //set and get methods
    //toString method to print the values the object's variable values
    }
     
     
    public class Planner {
    Appointment[] DayPlanner = new Appointment[20];
    DayPlanner[0] = new Appointment();              //Error: ']' expected | invalid method declaration; return type required
       
    }


Edited by Keyeszx

Share this post


Link to post
Share on other sites
Advertisement

You can't put code that actually does something like "DayPlanner[0] = new Appointment();" in just the class body. It has to be either in a method or a static block, though that would require DayPlanner to be a static member of Planner.

 

I'd change it to look like this:

public class Planner {
	private Appointment[] dayPlanner;



	public Planner(int maxAppointments) {
		dayPlanner = new Appointment[maxAppointments];
		dayPlanner[0] = new Appointment();
	}
}



// Create a planner with 20 appointments
new Planner(20);

However I would recommend using an ArrayList<Appointment> instead of a fixed array.

Share this post


Link to post
Share on other sites

Or an alternative would be to create the instances of Appointment when you create DayPlanner, e.g.

public class Planner {
    Appointment[] DayPlanner = new Appointment[] {new Appointment(), new Appointment(), new Appointment()};
}

DayPlanner is an array with 3 elements.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!