Java setters and getters

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

    The point of getters and setters is to let you limit/expand the scope or functionality of your property, independent of each other.


    You may want your 'name' property to be readonly outside of your PersonInfo class. In this case, you have a getter, but no setter. You can pass in the value for the readonly properties through the constructor, and retrieve that value through a getter:

    public class PersonInfo
    {
        //Your constructor - this can take the initial values for your properties
        public PersonInfo(String Name)
        {
            this.name = Name;
        }
    
        //Your base property that the getters and setters use to 
        private String name;
    
        //The getter - it's just a regular method that returns the private property
        public String getName()
        {
            return name; 
        }
    }
    

    We can use getName() to get the value of 'name' outside of this class instance, but since the name property is private, we can't access and set it from the outside. And because there is no setter, there's no way we can change this value either, making it readonly.


    As another example, we may want to do some validation logic before modifying internal values. This can be done in the setter, and is another way getters and setters can come in handy:

    public class PersonInfo
    {
        public PersonInfo(String Name)
        {
            this.setName(Name);
        }
    
        //Your setter
        public void setName(String newValue)
        { 
            if (newValue.length() > 10)
            {
                this.name = newValue;
            }
        }
    

    Now we can only set the value of 'name' if the length of the value we want to set is greater than 10. This is just a very basic example, you'd probably want error handling in there in case someone goes jamming invalid values in your method and complains when it doesn't work.


    You can follow the same process for all the values you want, and add them to the constructor so you can set them initially. As for actually using this pattern, you can do something like the following to see it in action:

    public static void main(String[] args)
    {
        PersonInfo myInfo = new PersonInfo("Slippery Sid",97,"male-ish");
        var name = myInfo.getName();
        System.out.printf("Your name is: " myInfo.getName() + " and you are a " myInfo.getSex());
    
        myInfo.setName("Andy Schmuck");
        System.out.printf("Your name is: " myInfo.getName() + " and you are a " myInfo.getSex());
    }
    

提交回复
热议问题