简体   繁体   中英

calling setter methods in my main application

package com.intermedix.domain;

public class Login {
      public Login(){}
        private String username;
        private String password;

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;

        }
}

Can i call the setUsername and setPassword in my main application like this.

Login lg = new Login();
lg.setUsername("somename");
lg.setPassword("somepassword");

Is this the right way of doing.

Yes that will work, alternatively you could provide a constructor that allows the username and password to be set when creating the Login object:

public Login(String username, String password)
{
    this.username = username;
    this.password = password;
}

and created thus:

Login lg = new Login("username", "password");

Yes it's the right way.

Why didn't you try to compile before asking?

Why not? You can always call setters of your beans if you need it. It is probably strange that user and password are hard coded in your example, but probably it is an example only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM