Results 1 to 14 of 14
  1. #1
    alacn's Avatar
    alacn is offline Senior Member
    Join Date
    Jun 2010
    Location
    UK. near London
    Posts
    118
    Rep Power
    0

    Default referencing objects via method help

    Ok im playing around with inheritence at the moment and ive been trying for the last 3 hours to try work out how to create objects efficiently but in the end my code doesnt work and im sure theres a much better way of doing it.
    Below is my code, ill explain after code what it is im trying to acheive and the error.

    PHP Code:
    import java.util.*;
    
    public class Main {
    
    
    static catFood filex[] = new catFood[3];
    
    static private int id;
    
    
    
        public static void createObject(Object _object, char _size, double _price){
    
            _object = new catFood(++id,_size,_price);
            
        }
    
        public static void main(String[] args) {
    
    
            createObject(filex[0],'s',4.99);
            createObject(filex[1],'m',6.99);
            createObject(filex[2],'l',9.99);
            System.out.print(filex[0].getSize());
            
    
            //List lstfilex = Arrays.asList(filex);
              
        }
    
    
    }
    Ok so basically i got an object array called felix and i basically want to fill all the attributes of the object up using a method that i made called createObject.
    so i passed the object and the values into the method, but when i compiled it i got a error
    PHP Code:
    Exception in thread "main" java.lang.NullPointerException
            at Main.main(Main.java:24)
    Java Result: 1
    Now i know why i got this error, its because i got the line

    PHP Code:
    _object = new catFood(++id,_size,_price);
    and it doesnt seem to realise that i am trying to create new instances of the felix objects

    so is there a way to fix this?

    my ultimate goals are:

    1) to get the method in my code above to work and
    2) to improve the method so that it can also accept other objects which refence to different classes. so for example rather than refering to new catFood, somehow use the same method to refence dogFood or something.
    i got a few ideas but i would like to get some pro feed back, plus this threads getting a bit long.


    thanks for reading
    Teaching myself java so that i can eventually join the industry! Started in June 2010

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    I think your problem is a call by value problem. filex[0] is a reference to an element in the array.
    You are setting the value of _object in the method. When the method exits, _object goes away.

    What line is line 24? The println()?

    A better technique would be to change the method to return the object:
    filex[0] = createObject('s',4.99); // create object and save in array
    Last edited by Norm; 08-07-2010 at 04:17 PM.

  3. #3
    alacn's Avatar
    alacn is offline Senior Member
    Join Date
    Jun 2010
    Location
    UK. near London
    Posts
    118
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    I think your problem is a call by value problem. filex[0] is a reference to an element in the array.
    You are setting the value of _object in the method. When the method exits, _object goes away.

    What line is line 24? The println()?

    A better technique would be to change the method to return the object:
    filex[0] = createObject('s',4.99); // create object and save in array
    oh yes that makes sense, i forgot about the local variables being terminated.
    What would you suggest if i wanted to initialise an object in refence to a different class in the same method?
    for example if i wanted to do dogbiscuits[0] = createObject('s',7.99);
    how could i make it initialise to the dogFood class within the createObject method?

    one idea that i had, was to pass an aditional byte of information into the createObject and then inside the createObject method do a conditional IF statment based on the value of the byte passed, which in turn decides which is the appropiate class to refence.

    but i didnt like this idea to much, does java offer more sophisticated solution?
    Teaching myself java so that i can eventually join the industry! Started in June 2010

  4. #4
    alacn's Avatar
    alacn is offline Senior Member
    Join Date
    Jun 2010
    Location
    UK. near London
    Posts
    118
    Rep Power
    0

    Default

    also im learning about lists. i know how to add additional information to lists but im having trouble working out the exact sytax to adding an additional object array element to a list for example

    PHP Code:
            foodOb[0] = new catFood(++id,"felix",'S',4.99);
            foodOb[1] = new catFood(++id,"felix",'M',5.99);
            foodOb[2] = new catFood(++id,"felix",'L',7.99);
            
            foodOb[3] = new dogFood(++id,"butchers",'S',7.99);
            foodOb[4] = new dogFood(++id,"butchers",'M',10.99);
            foodOb[5] = new dogFood(++id,"butchers",'L',14.99);        
            
            //System.out.print(filex[0].getSize());
            List lstFood = Arrays.asList(foodOb);
            lstFood.add();
    in the above code sniplet ive got 6 objects in an array and ive added it successfully to a List called lstFood. Now on the last line, what would parenthesis would i put in the lstFood.add(); to add an additional food object? ive tried a few differnt things but all come back in error and i couldnt find a specific example on google.

    my aim is to eventually stick the last line in a button event so that an end user could add additional objects on the fly. ie they wanted to add a new a dogFood object with XL size and different price

    thanks for reading
    Last edited by alacn; 08-07-2010 at 07:40 PM.
    Teaching myself java so that i can eventually join the industry! Started in June 2010

  5. #5
    alacn's Avatar
    alacn is offline Senior Member
    Join Date
    Jun 2010
    Location
    UK. near London
    Posts
    118
    Rep Power
    0

    Default

    any ideas anyone?
    Teaching myself java so that i can eventually join the industry! Started in June 2010

  6. #6
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    As far as I can tell, you cannot use add() on an existing array (the catFood[]) because Arrays cannot technically be resized. You have to do something ugly like this: How to resize an array in Java

    Best of luck.

  7. #7
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    ive tried a few differnt things but all come back in error
    What is the error?

  8. #8
    alacn's Avatar
    alacn is offline Senior Member
    Join Date
    Jun 2010
    Location
    UK. near London
    Posts
    118
    Rep Power
    0

    Default

    Quote Originally Posted by Zack View Post
    As far as I can tell, you cannot use add() on an existing array (the catFood[]) because Arrays cannot technically be resized. You have to do something ugly like this: How to resize an array in Java

    Best of luck.
    i tried the example in ur link but it came up with incapatability errors, so i changed the class name which is entered and returned from "Object" to "food"


    the reason why i done this was because to call it i used this code

    foodOb = resizeArray(foodOb,10);

    whereby foodOb is a userdefined object from the food class

    PHP Code:
       private static food resizeArray (food oldArray, int newSize) {
           int oldSize = java.lang.reflect.Array.getLength(oldArray);
           Class elementType = oldArray.getClass().getComponentType();
           food newArray = java.lang.reflect.Array.newInstance(
                 elementType,newSize);
           int preserveLength = Math.min(oldSize,newSize);
           if (preserveLength > 0)
              System.arraycopy (oldArray,0,newArray,0,preserveLength);
           return newArray; 
        }

    however i got an error on the line

    PHP Code:
    food newArray = java.lang.reflect.Array.newInstance(
                 elementType,newSize);

    so now im thinking that this method shouldnt of been modified at all and is designed only to work with the Object class? so how would i go about calling it?

    i tried something like Object fff = resizeArray(foodOb,10); with the original unmodified method and it worked, but then i didnt know how to use fff.
    All i wish to do is extend the foodOb length dynamically.
    Teaching myself java so that i can eventually join the industry! Started in June 2010

  9. #9
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    wish to do is extend the foodOb length dynamically.
    Normally this is done by creating a new array of the desired size and copying the contents of the old array into the new array and setting the old array reference to the new one.

    it came up with incapatability errors
    When you get errors, don't ignore them. Copy and paste them here
    Last edited by Norm; 08-08-2010 at 05:32 PM.

  10. #10
    alacn's Avatar
    alacn is offline Senior Member
    Join Date
    Jun 2010
    Location
    UK. near London
    Posts
    118
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    What is the error?
    hi norm, in response to your question, i tried this syntax

    lstFood.add(new food(++id,"butchers",'X',16.99));

    which didnt produce an error during design time but when i tried to compile i got this error

    PHP Code:
    Exception in thread "main" java.lang.UnsupportedOperationException
            at java.util.AbstractList.add(AbstractList.java:131)
            at java.util.AbstractList.add(AbstractList.java:91)
            at Main.main(Main.java:28)
    Java Result: 1
    Teaching myself java so that i can eventually join the industry! Started in June 2010

  11. #11
    alacn's Avatar
    alacn is offline Senior Member
    Join Date
    Jun 2010
    Location
    UK. near London
    Posts
    118
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    Normally this is done by creating a new array of the desired size and copying the contents of the old array into the new array and setting the old array reference to the new one.
    i tried this with the method that Zack supplied in the link in his response however the method only worked if i import and return an Object type and then when i tried to refence the foodOb to the Object type i got an incapability error. Maybe in doing this wrong?

    ill show you code

    original method, no errors here
    PHP Code:
       private static Object resizeArray (Object oldArray, int newSize) {
           int oldSize = java.lang.reflect.Array.getLength(oldArray);
           Class elementType = oldArray.getClass().getComponentType();
           Object newArray = java.lang.reflect.Array.newInstance(
                 elementType,newSize);
           int preserveLength = Math.min(oldSize,newSize);
           if (preserveLength > 0)
              System.arraycopy (oldArray,0,newArray,0,preserveLength);
           return newArray; 
        }

    calling method and then trying to assign fff to foodOb but i get an error on the last line
    PHP Code:
            
    Object fff = resizeArray(foodOb,10);
    foodOb = fff; //<<<<ERROR
    PHP Code:
    Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types
      required: food[]
      found:    java.lang.Object
            at Main.main(Main.java:41)
    Teaching myself java so that i can eventually join the industry! Started in June 2010

  12. #12
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    Look at the Arrays class's copyOf() method. All the messy stuff is in that method.

  13. #13
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    The error that you are having is because you are returning an Object, not an Object[].

    But I think perhaps Norm is right; that's probably the easier method for someone in your position.

  14. #14
    alacn's Avatar
    alacn is offline Senior Member
    Join Date
    Jun 2010
    Location
    UK. near London
    Posts
    118
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    Look at the Arrays class's copyOf() method. All the messy stuff is in that method.
    thanks norm, this has solved my problem. heres an example of the code that i got working which i will modify later so users can put their own parenthesis in.

    PHP Code:
            
    food foodObCopy[] = Arrays.copyOf(foodOb, foodOb.length+1);
    foodOb = foodObCopy;
    foodOb[foodOb.length-1] = new dogFood(++id,"butchers",'x',17.99);
    for anyone else who comes across this thread in future with same problem, ill explain code above.
    An array of object references called foodObCopy[] is created and copies the object references foodOb using the Arrays.copyOf method which is found in java.util.Arrays;. in the second value passed (length+1) i basically added an additional space in the array stack,so i basically said make the copy the same length as the original plus one extra space, which refers to a null value.
    i then took the original foodOb and copied the refences from foodObCopy which now means foodOb has an extra space too.
    the final line i basically initiliase the newly created last null space and make it point to an object and pass some values into that object.
    if i were to place this into a button event, then everytime the user clicks the button, a new array space would be created and then a new object would be initialised into that new array space.
    and u could change "butchers" to something like textField.getText() so the values can be filled in dynamically from a GUI.
    Teaching myself java so that i can eventually join the industry! Started in June 2010

Similar Threads

  1. referencing files in .exe
    By minime12358 in forum Advanced Java
    Replies: 7
    Last Post: 07-26-2010, 08:28 PM
  2. How do i do this method(objects)
    By Meta in forum New To Java
    Replies: 1
    Last Post: 04-19-2010, 10:38 PM
  3. referencing objects from static method
    By talktofrank in forum New To Java
    Replies: 4
    Last Post: 10-26-2009, 06:09 PM
  4. Static method cannot make new objects?
    By zerkz in forum New To Java
    Replies: 2
    Last Post: 10-15-2009, 03:17 AM
  5. Replies: 6
    Last Post: 04-05-2009, 11:28 PM

Posting Permissions

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