Results 1 to 4 of 4
  1. #1
    Viinnyk is offline Member
    Join Date
    Jul 2013
    Posts
    2
    Rep Power
    0

    Question Calling a list from outside the class

    I have this ArrayList defined in one class:
    Java Code:
    public class ClassA {
     
    	public List<Object> objects = new ArrayList<Object>(16);
    and would like to call:
    Java Code:
    blocks.add()
    in another class but cannot figure out how. I was thinking it would be something like:
    Java Code:
    public class ClassB{
    	
    	void doStuff(){
    		ClassA.objects.add();
    	}
    }
    but that doesn't work. Any suggestions on how to fix this?

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,235
    Rep Power
    19

    Default Re: Calling a list from outside the class

    To access an instance member, you need an instance of a class.

    That said, it's generally frowned on to expose the internals of a class via public variables. The norm is to provide public (or as appropriate protected or default) methods that store/retrieve state in private variables.

    So your ClassA could have a public void add(whatever) method which would do the actual addition to the List.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  3. #3
    Viinnyk is offline Member
    Join Date
    Jul 2013
    Posts
    2
    Rep Power
    0

    Default Re: Calling a list from outside the class

    That sounds much better than what I had in mind. Thank you!

  4. #4
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,235
    Rep Power
    19

    Default Re: Calling a list from outside the class

    You're welcome, and do come back when you have another question.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

Similar Threads

  1. Replies: 8
    Last Post: 04-18-2012, 04:58 PM
  2. Replies: 3
    Last Post: 01-26-2012, 11:20 PM
  3. Child-Class Calling a Method in a Parent-Class
    By Blah_ in forum New To Java
    Replies: 5
    Last Post: 09-29-2009, 02:48 AM
  4. Replies: 2
    Last Post: 12-19-2008, 02:20 AM
  5. Calling a method on original class from created class
    By kpedersen in forum Advanced Java
    Replies: 4
    Last Post: 08-20-2008, 12:25 AM

Tags for this Thread

Posting Permissions

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