Results 1 to 2 of 2
  1. #1
    lockmac is offline Member
    Join Date
    Aug 2007
    Posts
    8
    Rep Power
    0

    Default passing an array into an instance

    Hi. I am just wandering how do I pass an array from one class into another class via a constructor?

    In the class that i collect my information in, I have the following code:

    Java Code:
    units[Unit.unitCount] = new Unit(name,code,sem1,sem2,campusCount,campuses);
    the name of the array is campuses.

    in my Unit class, my Constructor looks like this...

    Java Code:
    	public Unit(String iName, String iCode, char iSemester1, char iSemester2, int iCampusCount)
    	{
    		name=iName;
    		code=iCode;
    		campuses= new String[10];
    		semester1=iSemester1;
    		semester2=iSemester2;
    		unitCount++;
    		campusCount=iCampusCount;
    but when i try to do a toString to print off values of the array, every value comes up as null, so I can only assume that they are not being set correctly in the first place.

    Any help would greatly be appreciated.

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Java Code:
    new Unit(name, code, sem1, sem2, campusCount, campuses);
    
    Unit(String iName, String iCode, char iSemester1, char iSemester2, int iCampusCount)
    {
    	name=iName;
    	code=iCode;
    	campuses= new String[10];
    	semester1=iSemester1;
    	semester2=iSemester2;
    	unitCount++;
    	campusCount=iCampusCount;
    These are different constructors. The top one has six arguments. The bottom on has five arguments. The top statement will not call the bottom constructor.
    In the bottom one, since campuses is instantiated
    Java Code:
    campuses= new String[10];
    but not initialized by assignment of constructor local variable/arguments
    Java Code:
    this.campuses = campuses;
    or by initialization of each element
    Java Code:
    for(int j = 0; j < campuses.length; j++)
        campuses[j] = "";
    I would expect all elements to be null.

Similar Threads

  1. Instantiation using an instance factory method
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 03-29-2008, 12:35 PM
  2. Create different instance of a tablemodel
    By Bill in forum AWT / Swing
    Replies: 6
    Last Post: 03-27-2008, 03:49 PM
  3. New Instance for SWT
    By srinivasa_v in forum SWT / JFace
    Replies: 1
    Last Post: 08-08-2007, 01:02 AM
  4. problems with Instance Data
    By paty in forum New To Java
    Replies: 2
    Last Post: 08-02-2007, 05:45 PM
  5. Instance variable
    By Jack in forum New To Java
    Replies: 2
    Last Post: 07-04-2007, 04:00 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •