Java setters and getters

后端 未结 7 1625
情书的邮戳
情书的邮戳 2020-12-06 22:42

I have been struggling with setters and getters in java for quite a long time now.

For instance, if I want to write a class with some information as name, sex, age

相关标签:
7条回答
  • 2020-12-06 23:29

    here's how you do it:

    public class PersonInfo {
    
        private String name;
        private String sex;
        private int age;
    
    
        /** GETTERS **/
    
        public String getName(){
            return name;
        }
    
        public String getSex(){
            return sex;
        }
    
        public int getAge(){
            return age;
        }
    
        /** SETTERS **/
    
        public void setName(String name){
            this.name = name;
        }
    
        public void setSex(String sex){
            this.sex = sex;
        }
    
        public void setAge(int age){
            this.age = age;
        }
    }
    
    class Test{
        public static void main(String[] args){
            PersonInfo pinfo = new PersonInfo();
            pinfo.setName("Johny");
            pinfo.setSex("male");
            pinfo.setAge(23);
    
            //now print it
    
            System.out.println("Name: " + pinfo.getName());
            System.out.println("Sex: " + pinfo.getSex());
            System.out.println("Age: " + pinfo.getAge());
    
        }
    }
    

    Or you can add this as well:

    @Override
    public String toString(){
        return "Name: " + this.name + "\n" +
                "Sex: " + this.sex + "\n" +
                "Age: " + this.age;
    }
    

    and then just to a .toString

    EDIT:

    Add this constructor in the class to initialize the object as well:

    public PersonInfo(String name, String sex, int age){
        this.name = name;
        this.sex = sex;
        this.age = age;
    }
    
    0 讨论(0)
提交回复
热议问题