Junior — Middle
What method can be used to ensure the hiding of a password within a class for data protection?
sobes.tech AI
Answer from AI
To hide a password inside a class and protect the data, the password should be made a private field of the class and not provide direct access to it from outside. Instead, you can implement methods for password verification or encryption.
Example:
public class User {
private String password; // private field
public User(String password) {
this.password = hashPassword(password); // store hashed password
}
private String hashPassword(String password) {
// simple hash example (use strong algorithms in real cases)
return Integer.toString(password.hashCode());
}
public boolean checkPassword(String input) {
return hashPassword(input).equals(this.password);
}
}
Thus, the password is not stored in plain text, and access to it is controlled through class methods.