Hei
Hei

Reputation: 7

Confusion with java objects

I am a beginner in java and I am currently using Netbeans IDE and I have some confusion here. I wrote down the following codes:

public class Try {

    public static int AA;
    public static int BB;

    Try(int a, int b)
    {
        AA=a;
        BB=b;
    }

    int calculate()
    {
        int c;
        c=Try.AA + Try.BB;
        System.out.println(c);
        return 0;
    }

    public static void main(String[] args) {
        Try a = new Try(1,2);
        Try b = new Try(2,3);
        a.calculate();
        b.calculate();
        // TODO code application logic here
    }
}

Well, just a simple program that adds two integers and here is the output:

5
5

I was expecting it to be

3
5

So, where have i gone wrong? Here is the screenshot

Upvotes: 0

Views: 60

Answers (2)

David Pérez Cabrera
David Pérez Cabrera

Reputation: 5068

AA and BB attributes are shared between all objects (and they were rewritten).

package pkgtry;

/**
 *
 * @author HeiLee
 * 
 */
public class Try {

 /* there is the mistake,

    public static int AA; 
    public static int BB;

    This attributes are shared between all objects.
*/
    public int AA; 
    public int BB;

     Try(int a, int b)
    {
        AA=a;
        BB=b;
    }
     int calculate()
    {
        int c;
        c=AA + BB;
        System.out.println(c);
        return 0;
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Try a = new Try(1,2);
        Try b = new Try(2,3);
        a.calculate();
        b.calculate();
    }

}

Upvotes: 1

Zircon
Zircon

Reputation: 4707

AA and BB are static which means they belong to the class, not each instance. Essentially, these two variables are shared across all instances of Try. When you instantiated the second Try object, the original two values were overwritten.

Making the two variables non-static will result in the calculations you're expecting.

Upvotes: 4

Related Questions