简体   繁体   中英

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

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.

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();
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM