Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Java classes as variables of other classes

Options
  • 26-08-2012 5:43pm
    #1
    Registered Users Posts: 7,838 ✭✭✭


    I'm just new to java, like last week. I'm trying to solve a problem without really learning the language first. Good idea, I know.

    I'm having a problem with using instances of 1 class in another and getting cannot find symbol errors.

    Can I make an instance of one class a variable or attribute of another class?

    I get the "cannot find symbol" error when I try to use the changeGear() method in the drive() method. This is not the actual implementation, just an example.


    [php]
    public class Car {

    private Gearbox[] gb;

    public Car() {
    gb = new Gearbox[5];
    }

    public void drive(int g) {

    gb.changeGear(g);

    }

    }[/php][PHP]
    public class Gearbox {

    int var1 = 0;

    public Gearbox {

    // constructor stuff works fine

    }
    public void changeGear(int g) {

    //change var1

    }

    }[/PHP]


Comments

  • Registered Users Posts: 9,094 ✭✭✭Royale with Cheese


    What you're doing will work fine. Your problem is that gb is a reference to an array of type Gearbox rather than an actual Gearbox object. When you try gb.changeGear() it complains because you're trying to execute that method on an array.

    Instead of this:
        private Gearbox[] gb;
    
        public Car() {
           gb = new Gearbox[5];
        }
    
    Try this:
        private Gearbox gb;
    
        public Car() {
           gb = new Gearbox();
        }
    


  • Registered Users Posts: 7,838 ✭✭✭Nulty


    Thanks.

    I need to pass a parameter to the instantiation for Gearbox, say, to define the number of gears it has, that's what I thought the square brackets were for. Actually, thats whats confused me I think. The parameter is to assign the size of an array in the Gearbox class.

    My constructor should have looked like this:

    [PHP]
    public class Gearbox {

    // array of speeds will be initialized by constructor parameter
    boolean[] speeds;

    public Gearbox(int gears) {

    speeds[gears];

    // constructor stuff works fine
    // initialise all to false except neutral or whatever

    }
    public void changeGear(int g) {

    //change var1

    }

    }[/PHP]and then in the car:

    [php]
    public class Car {

    private Gearbox gb;

    public Car() {
    gb = new Gearbox(5);
    }

    public void drive(int g) {

    gb.changeGear(g);

    }

    }[/php]

    I think thats working now, thanks for pointing me in the right direction!


Advertisement