使用setter和getter JAVA从另一个类访问变量 [英] Accessing variables from another classes with setter and getter JAVA

查看:59
本文介绍了使用setter和getter JAVA从另一个类访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的项目的一个非常简单的示例,它的规模要大得多.

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

任务:

  • 密码将通过setpassword方法设置.

  • The password will be set at the setpassword method.

getpassword方法将返回密码.

The getpassword method will return the password.

在sendmail类中调用该密码,以便通过电子邮件发送给用户以使用新的凭据登录.

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

但是,当我运行整个代码时,除了sendmail类无法从users类的getpassword方法访问密码之外,其他所有功能都可以正常工作.

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:

用户类>>>>>

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();

}
}

发送邮件类>>>>

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
 }
 }

主要注册类>>>>

public class SignupMain {

public static void main(String[] args) {

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

 }

推荐答案

请遵循标准的编码约定.我使用标准编码约定更改了您的代码.只需复制粘贴即可,

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

用户分类

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;
 }
}

注册课程

public class Signup {

public void settingPassowrd(){

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

    SendMail mail1 =new SendMail(user1);
    mail1.Sendsmail();

}
}

SendMail类

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
}
}

测试代码的主类

 public class SignupMain {

public static void main(String[] args) {

 Signup signup1= new Signup();
 signup1.settingPassowrd();
}

}

这篇关于使用setter和getter JAVA从另一个类访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆