So what I am trying to do is this:
Write a User class
A User:
My code so far:
public class User{
public String id;
public String userPermissions;
public String actualName;
public User(String username, String userType, String name){
id = username;
userPermissions = userType;
actualName= name;
}
public String getUsername(){
return id;
}
public String getUserType(){
return userPermissions;
}
public String getName(){
return actualName;
}
public enum UserType{
admin, editor, user;
}
public void setUserType(String input){
userPermissions = input;
}
}
What do I need to do to get this to work? I do not know how to make it so the only usertypes that can be chosen are admin, editor or user.
You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values. Examples would be things like type constants (contract status: "permanent", "temp", "apprentice"), or flags ("execute now", "defer execution").
You can use Enum as well as any other Object as key. 2. Performance : EnumMap is a specialized Map implementation for use with enum type keys. EnumMaps are represented internally as arrays.
Update: It's possible to have setters in enum types. Save this answer.
If the enum is only used within one class, it should be placed within that class, but if the enum is used between two or more classes, it ought to either be in it's own code file, or in a conglomerated code file that contains all the enum for a particular assembly.
You have to change your types to this enum:
public class User {
public enum UserType {
ADMIN, EDITOR, USER;
}
public String id;
public UserType userPermissions;
public String actualName;
public User(String username, UserType userType, String name) {
id = username;
userPermissions = userType;
actualName= name;
}
public String getUsername() {
return id;
}
public UserType getUserType() {
return userPermissions;
}
public String getName() {
return actualName;
}
public void setUserType(UserType input) {
userPermissions = input;
}
}
Because you have already declared an enum type to represent the possible values for userType, you've already gone a long way to solving this problem.
If you declare a variable of type UserType, then the only possible values must be one of the defined enum constants.
To restrict the input to your setPermissions method, all you have to do is change to the following:
public class User{
public String id;
public String userPermissions;
public String actualName;
public User(String username, String userType, String name){
id = username;
userPermissions = userType;
actualName = name;
}
public enum UserType{
ADMIN, EDITOR, USER;
}
public void setUserType(UserType type){
userPermissions = type.toString();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With