0

I'm trying to create a bunch of objects with unique IDs. My first idea for implementing this was to have a static variable that counted the amount of objects. Each time an object is created, the static variable is increased by one and written down as the ID of the object.

Gleefully, I implemented the code thusly:

    public class Order {
        static int totalOrdersPlaced;
        public int orderID;

        public void Order() {
            totalOrdersPlaced++;
            orderID = totalOrdersPlaced;
        }
    }

...which throws a "cannot make a static reference to the non-static field" error for reasons I roughly understand. But I can't quite figure out how to implement what I want.

tl;dr: How to I make the program get the current value of a static variable and store it?

3 Answers 3

3

The code in your question compiles. Does your real code have public static void Order() instead?

Either way, I'm guessing you meant to do this in a constructor, so remove the void:

public class Order {
    private static int totalOrdersPlaced;
    public final int orderID;

    public Order() {
        totalOrdersPlaced++;
        orderID = totalOrdersPlaced;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh. Oh dear. Yes, that was... The void was not supposed to be... I feel a bit dumb now. Thanks for the help. (and no, my real code did not have public static void Order())
1
 public class Order {
    static int totalOrdersPlaced;
    public int orderID;

    public void Order() {
        totalOrdersPlaced++;
        orderID = totalOrdersPlaced;
    }
}

will work if you convert Order() method to a constructor.(Remove the void).

Here is a test code:

 public class Order {
    static int totalOrdersPlaced;
    public int orderID;

    public Order() {
        totalOrdersPlaced++;
        orderID = totalOrdersPlaced;
    }
    public static void main(String[] args) {
    Order order = new Order();
    System.out.println(order.totalOrdersPlaced);
    Order order2 = new Order();
    System.out.println(order2.totalOrdersPlaced);
}
}

Proof: http://ideone.com/n06npg

Comments

1

Remove void in the

 public void Order() {
            totalOrdersPlaced++;
            orderID = totalOrdersPlaced;
        }

Constructor should not have return type

.. originally identified by MattBall

Generate getters and setters for the required variable and get the value by using getter method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.