Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jan 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Need help with java code! Beginner

    Hi I am a beginner with Java have been in school for a month now.
    I have a question about a school project that needs to be done.
    We are supposed to create objects that can be either a jewellry, stock or an item. These are all subclasses to Things. We also have a class called Person(they are the owners of Things), and in that class we are supposed to have an arraylist<Things>.
    My question is now. If I create an object of jewellry in the main method, how can i add it to the ArrayList<Things> in person-class.

    Please be patient with me because Im very new to this, and its not really my favourite subject


  • #2
    Codeasaurus Rex
    Join Date
    Jun 2008
    Location
    Redmond, WA
    Posts
    659
    Thanks
    31
    Thanked 100 Times in 94 Posts
    Assuming your class Jewelery extends Things you should be able to just add it into ArrayList<Things>.

    So, your Java class for Jewelery would have to start something like this:

    Code:
    public class Jewelery extends Things {
    With inheritance (the extends attribute), if B extends A, and there exists ArrayList<A>, then B can be added to ArrayList<A>.

    (Think of inheritance as a more specific version of a parent class. For example Rose extends Flower)

    So, you should be able to use the Java API on ArrayList to add the object, for example:

    Code:
    Jewelery myJewelery = new Jewelery();
    
    // Invoking add( Object o ) adds the object to the end of the list
    myThingsArrayListObject.add( myJewelery );
    Where myThingsArrayListObject is the object created in Person with the array list.

    For detailed methods with the ArrayList API, consult the Java Doc: http://download.oracle.com/javase/1....ArrayList.html

    Moreover, if you have problems saying something like "Cannot reference this from a static context" then please post your complete error here with relevant lines of code and I can help you work through that. If you're new to Java and trying to modify a class' object from the main() method then you'll probably run into that problem.

    Hope this helps!
    Unless otherwise stated, any code posted is most likely untested and may contain syntax errors.
    My posts, comments, code, and suggestions reflect only my personal views.
    Web Portfolio and Code Snippets: http://shanechism.com


  •  

    Posting Permissions

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