Results 1 to 5 of 5
  1. #1
    Java-Guy is offline Member
    Join Date
    Jan 2011
    Posts
    9
    Rep Power
    0

    Question Accessing Constructor from another Class

    I need to access a constructor called "car" from a test class:

    public class car {

    private ArrayList<Integer> cs;

    public car(ArrayList<Integer> cs) {
    this.cs=cs;
    }
    }

    I tried doing this (which didn't work):

    public class testcar {

    car c1 = new car();
    c1.car();
    }

    Any ideas?
    Thanks.

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default

    Java Code:
    c1.car();
    You cannot call a constructor. The above line assumes you are trying to call a method called car which obviously doesn't exist. The new operator calls the constructor for you. So all you need is the first line of code.

  3. #3
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default

    I just realised you are also missing the parameter that the constructor is expecting to be passed to it.

  4. #4
    goldest's Avatar
    goldest is offline Senior Member
    Join Date
    Oct 2009
    Location
    Pune, India
    Posts
    469
    Rep Power
    6

    Wink

    Quote Originally Posted by Java-Guy View Post
    I tried doing this (which didn't work):

    public class testcar {

    car c1 = new car();
    c1.car();
    }

    Any ideas?
    Thanks.
    You need to pass the ArrayList to the car constructor, like,
    Java Code:
    car c1 = new car(yourArrayList)

    Use proper naming conventions for your code. Refer here: Naming Conventions.

    Goldest
    Last edited by goldest; 01-19-2011 at 05:49 AM. Reason: Thanks Junky, Modified.
    Java Is A Funny Language... Really!
    Click on * and add to member reputation, if you find their advices/solutions effective.

  5. #5
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default

    <cough>
    Java Code:
    car c1 = new car(yourList);

Similar Threads

  1. Accessing class defined within a constructor
    By kwaspl in forum New To Java
    Replies: 4
    Last Post: 12-21-2009, 03:35 PM
  2. Replies: 8
    Last Post: 03-21-2009, 10:34 AM
  3. [SOLVED] Accessing private constructor
    By piyu.sha in forum New To Java
    Replies: 2
    Last Post: 10-06-2008, 06:45 AM
  4. Replies: 0
    Last Post: 12-19-2007, 10:10 AM
  5. Replies: 0
    Last Post: 12-19-2007, 10:01 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
  •