1

I'm not quite sure what to call it, but essentially, when I run this code:

public class test {

    static Device one;
    static Device two;

    public static void main(String[] args) throws Exception {

        one = new Device("One", "ONE");
        System.out.println(one.getName());
        two = new Device("Two", "TWO");

        System.out.println(one.getName());
        System.out.println(two.getName());

    }
}

The output is:

ONE  
TWO
TWO

when it should be:

ONE
ONE
TWO

The device object is pretty simple, it just receives two strings, the second being the "name" that I'm asking it to print. I've done OOP before, but I feel like I'm just forgetting some important aspect, but can't seem to figure it out. Any help is appreciated, thanks!

And here is the device constructor:

public Device(String iP, String Name) {
    //Set the IP address
    IP = iP;
    //Set the device's name
    name = Name;
    // Set the string version of the device (for transmitting)
    stringVersion = IP + ";" + name;
}
4
  • 4
    If you could print the Device constructor, it would help us answer. Commented Jul 6, 2012 at 16:02
  • 2
    Show the whole Device class. Are IP and Name static? Commented Jul 6, 2012 at 16:05
  • Yes, they are, thank you so much. Man I forgot about that... Thanks again! Commented Jul 6, 2012 at 16:07
  • 1
    You should be able to implement this without any static fields. I suggest you use local variables and final non-static fields where possible. Commented Jul 6, 2012 at 16:08

2 Answers 2

8

Looks like you've used static fields in Device too. These are not instance fields. Mutable static fields should be avoided.

Sign up to request clarification or add additional context in comments.

Comments

0

From the comments:

Show the whole Device class. Are IP and Name static? – assylias 2 mins ago

Yes, they are

Your device static members get reinitialized whenever you instantiate a new instance of Device that's why you get that behavior. You can have one and two as static but you shouldn't have mutable member variables static

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.