I already did some research about this topic (e.g. Difference between constructor and getter and setter). The main difference between getter- and setter-methods and constructor is clear for me. I just want to create a simple login window (without a db in background) but I have some issues with my getter and setter methods.
I created a class called user
and a class called admin
. The user
class has a constructor and getter and setter methods:
public class User {
private String fName;
private String nName;
private String password;
private String username;
private int group;
//Constructor
public User(String username, String fName, String nName, String password, int group){
this.username = username;
this.fName = fName;
this.nName = nName;
this.password = password;
this.group = group;
}
//getter and setter methods here
In an other class I tried to create a new user:
public class Admin extends User{
private String username = "admin";
private String fName = "name";
private String nName = "secondName";
private String password = "password";
private int group = 1;
public Admin(String username, String fName, String nName, String password, int group){
super(username, fName, nName, password, group);
}
User admin = new User(username, fName, nName, password, 1);
}
Now I can't use for example admin.setUsername("admin1");
. Why is this?
You actually can do that just make sure your getters and setters are public,an easy way to ensure your getters and setters are correct is to right click in your class->source->generate getters and setters then choose which attributes you want to be read and write, However if your intention with this line
User admin = new User(username, fName, nName, password, 1);
is to create a new admin with these attributes
username = "admin";
fName = "name";
nName = "secondName";
password = "password";
group = 1;
maybe try instead:
either passing the values to the constructor directly without the variables
User admin = new User ("admin","name","secondName",password,1);
or if you want for these to be the default values that an admin object is to have every time you create it then you can do this in the constructor:
public Admin (){
super("admin","name","secondName",password,1);
then
Admin admin = new admin();
then you can change the username like you want and if you want to check that it changed use
System.out.println(admin.getUsername());
in both cases you don't really need to create the instance variables as they are inherited from user class.