-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.

Snowman
  • 17
  • 2
  • 3
    Yes, simply remove the static modifier on the Variable and method – Felix Nov 07 '20 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. – Mark Rotteveel Nov 07 '20 at 19:11
  • 1
    Related: [Why is it possible for objects to change the value of class variables?](https://stackoverflow.com/questions/29050441/why-is-it-possible-for-objects-to-change-the-value-of-class-variables) – Mark Rotteveel Nov 07 '20 at 19:13
  • BTW take care of java naming conventions. Class names should start with upper case character. – Jens Nov 07 '20 at 19:23

1 Answers1

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

}
zmn
  • 141
  • 1
  • 1
  • 13