Search code examples
javamethodsgetsetgetter-setter

Accessing variables from another classes with setter and getter JAVA


This is a very simple example of my project which is a lot more bigger in scale.

Tasks:

  • The password will be set at the setpassword method.

  • The getpassword method will return the password.

  • The password is called at sendmail class in order to be send via email to the user to log in with the new credentials.

But When I run the whole code everything works except that the sendmail class won't access the password from the getpassword method in users class.

I put a simple version of my code:

users class >>>>>

public class  users {


private String password;


public users (){}

// GETTING PASSWORD
public String getpassword(){

    return password;
}


// SETTING PASSWORD
 public void setapassword(String password){
     this.password=password;
 }




}

Signup class>>>>>>

public class signup {

public void signsup(){

    users  user1 =new users();
    user1.setapassword("player"); 

    sendmail mail1 =new sendmail();
    mail1.Sendsmail();

}
}

sendmail class>>>>

public class sendmail   {

public void  Sendsmail(){

    users user1 =new users(); // object

    user1.getpassword(); //getting password 

 System.out.println(user1.getpassword()); // If print here I get null
 }
 }

Main signup Class>>>>

public class SignupMain {

public static void main(String[] args) {

     signup signup1= new signup();
     signup1.signsup();
   }

 }

Solution

  • Please follow the standard coding conventions. I changed your code with standard coding conventions. just copy paste it , it will work

    Users class

    public class  Users {
    private String password;
    public users (){}
    // GETTING PASSWORD
    public String getpassword(){
    
        return password;
    }
    // SETTING PASSWORD
     public void setapassword(String password){
         this.password=password;
     }
    }
    

    Signup class

    public class Signup {
    
    public void settingPassowrd(){
    
        Users  user1 =new Users();
        user1.setapassword("player"); 
    
        SendMail mail1 =new SendMail(user1);
        mail1.Sendsmail();
    
    }
    }
    

    SendMail class

    public class SendMail   {
        private Users user1;
        SendMail(Users user1){
            this.user1 = user1
        }
        public void  sendMail(){
        user1.getpassword(); //getting password 
        System.out.println(user1.getpassword()); // If print here I get null
    }
    }
    

    Main class to test the code

     public class SignupMain {
    
    public static void main(String[] args) {
    
     Signup signup1= new Signup();
     signup1.settingPassowrd();
    }
    
    }