1

Like I have such code:

class myobj {
    public static int i;

    public myobj(int _i) {
        i = _i;
    }
}

public class mainclass {
    public static void main(String[] args) {
        myobj a = new myobj(1);
        myobj b = new myobj(2);

        System.out.println(b.i); // Prints 2 - expected
        System.out.println(a.i); // Prints 2 - unexpected
    }
}

And I want a.i to be 1.

How can I make a 'new' object?

Jimmy2002
  • 11
  • 1

4 Answers4

4

Remove the static declaration. Declaring something as static means that it will be shared across all instances of a class. So in your code, both a and b were using the same i variable. If we just remove the static modifier, your code works as expected.

class myobj {

    public int i;

    public myobj(int _i) {
        i = _i;
    }
}

public class mainclass {

    public static void main(String[] args) {
        myobj a = new myobj(1);
        myobj b = new myobj(2);

        System.out.println(b.i); // Prints 2 - expected
        System.out.println(a.i); // Prints 2 - unexpected
    }
}
therealrootuser
  • 10,215
  • 7
  • 31
  • 46
2

Make this:

public static int i;

this:

public int i;

Everything else is fine.

BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
2

Given what you've asked change this

public static int i;

to

public int i;

Because a static field is shared by all instances of myobj.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

if you write your class that way

public static int i;

only one i will be created and this i will be shared with all object of myobj ever created.That what static key word means and used for. Read this thread for better understanding. I if want i once a myobj created remove the static keyword

public int i;
Community
  • 1
  • 1
Saif
  • 6,804
  • 8
  • 40
  • 61