-1

I have a class with a static variable x and a method to set a value.

public class mainclass
{
 
    public static int x;
 

    public static int newvalue( int y )
    {
        
    x = y;  
     return y;

    
    }
    
}

I have another class to store integer value

public class instance {

    public static void main(String[] args) {
            
        mainclass main = new mainclass();
        mainclass main1 = new mainclass();
        main.newvalue( 1 );
        System.out.println("x = " + main.x);
        int y = main.x;
        main1.newvalue( 2 );
        System.out.println("x = " + main1.x);
        
        System.out.println("x = " + main.x);
        
    }

}

It gives output

main: x = 1
main1: x = 2
main: x = 2

Now what I like to have an output

main: x = 1
main1: x = 2
main: x = 1

Is it possible. Please.

4
  • 3
    Yes, simply remove the static modifier on the Variable and method Commented Nov 7, 2020 at 19:04
  • Although it is possible, you shouldn't call static methods or fields on an instance. This causes exactly the confusion you have right now. static means it belongs to the class, not to a specific instance. Commented Nov 7, 2020 at 19:11
  • 1
    Related: Why is it possible for objects to change the value of class variables? Commented Nov 7, 2020 at 19:13
  • BTW take care of java naming conventions. Class names should start with upper case character. Commented Nov 7, 2020 at 19:23

1 Answer 1

2

you need to modify the maincalss class as shown below:

public class mainclass {

    public int x;

    public int newvalue( int y ) {
    
    x = y;  
     return y;
 
    }

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.