Java setters and getters

后端 未结 7 1664
情书的邮戳
情书的邮戳 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:22

    In personInfo:

    public Person(String n, int a, String s){
        this.name=n;
        this.age=a;
        this.sex=s;
    }
    public String getName(){
       return this.name;
    }
    public int getAge(){
       return this.age;
    }
    public String getSex(){
       return this.sex;
    }
    public void setName(String n){
       this.name = n;
     }
     public void setAge(int a){
       this.age = a;
     }
     public void setSex(String s){
       this.sex = s;
     }
    

    Then fix the print statement:

    System.out.println("Your name is: " + myInfo.getName() + " and you are a " +        myInfo.getSex());
    

提交回复
热议问题