简体   繁体   中英

How to change the value of variable inside a class using another class in java?

I have here user login and change password , now in change password class button save action event I have code like this

 if(txtCurrentPassword.getText().equals(LoginFrm.defaultPassword) &&
           txtNewPassword.getText().equals(txtConfirmPassword.getText())){
           // CODE SHOULD BE HERE TO PASS THE NEW PASSWORD VALUES  TO USER LOGIN FORM IF THE CONDITION IS TRUE
           JLabel message = new JLabel("You are successfully changed your password");
           message.setFont(new Font("Arial", Font.PLAIN, 16));
           JOptionPane.showMessageDialog(null, message);
   }

Now as you can see at the condition above there is a public static variable called defaultPassword,this variable is at the User login class, and this variable has a String value the default password of the user. Now how to change the value of variable defaultPassword inside a class user login using changePassword class? Any suggestion would help or tell me if there's something to modify in this idea?Thank you

Given that defaultPassword is a publicly accessible static field in the LoginFrm class, you can directly update its reference to the new password String. The below snippet should work.

if(txtCurrentPassword.getText().equals(LoginFrm.defaultPassword) &&
       txtNewPassword.getText().equals(txtConfirmPassword.getText())){
       LoginFrm.defaultPassword = txtNewPassword.getText();
       JLabel message = new JLabel("You are successfully changed your password");
       message.setFont(new Font("Arial", Font.PLAIN, 16));
       JOptionPane.showMessageDialog(null, message);
}

If it's a public static variable, you should be able to access it through ClassName.variableName. However, this is not necessarily best practice. It may be wise to privatize that variable and create methods for getting/setting it.

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