Leroy
Leroy

Reputation: 9

How do I create an object from a specific class and change its attributes by using methods in java

public class Forklift{
    double height;
    Forklift fl_1, fl_2;
    
    Forklift(){
        fl_1 = new Forklift();
        fl_2 = new Forklift();
    }

    void raise(){
        height += 10;
    }
    void lower(){
        height -= 10;
    }
}

I'm currently using BlueJ. I want to create two objects with the attribute 'height' and I want to use the methods raise() and lower() to change the value of that attribute. Can someone please help me? I don't know why it's not working

Upvotes: 0

Views: 47

Answers (1)

Jhanzaib Humayun
Jhanzaib Humayun

Reputation: 1183

Are you trying to do something like this?

public class Forklift{
    double height;
    
    Forklift(){
        height=0;
    }

    void raise(){
        height += 10;
    }
    void lower(){
        height -= 10;
    }
}

I dont understand why you are creating a forklift in the forklift constructor. That just gives you an infinite loop.

Edit: If you want to create two instances of the class, just use:

Forklift forklift1 = new Forklift();
Forklift forklift2 = new Forklift();

somewhere outside the class. Now you have two instances of the class.

Upvotes: 2

Related Questions