Java思维---set()方法与get()方法

304 阅读2分钟

一、set()方法与get()方法

JAVA面向对象编程具有封闭性和安全性。

封闭性即对类中的域变量进行封闭操作,即用private来修饰他们,如此一来其他类则不能对该变量访问。

这样我们就将这些变量封闭在了类内部,这样就提高了数据的安全性。

当我们想要操作这些域变量时,我们可以通过两种方法:

  • 第一种是通过public方式的构造器(或称构造函数),对象一实例化就对该变量赋值

  • 第二种就是通过set()方法和get()方法【其中,set是设置的意思,而get是获取的意思】

举例来说:我们定义一个学生类,希望对这个学生类中的name、score变量进行操作,又想要对实例进行的操作进行限制,如限制成绩在0-100分之间,而不能输入不符合规定的内容。此时我们将学生成绩定义为private变量,实例不能直接操作变量,接着我们提供set()方法和get()方法,实例可以通过这两个方法,在规则有所限定的前提下操作变量,此时提高域变量的安全性,也保证了域变量的封装性。


二、public下的不安全情境

public class Student {
    ppublic String name;
    public int score;
    public void intor(){
        System.out.println("我的名字是"+name+",我的成绩是"+score+"分。");
    }
public class TestStudent {
    public static void main(String[] args) {
        Student stu1=new Student();
        Student stu2=new Student();
        stu1.name="Jack";
        stu2.name=jkdsabshvnasjdnv;	// 姓名输入不规范依旧能够录入
        stu1.Score=90;
        stu2.Score=66666;	// 成绩输入不规范依旧能够录入
        stu1.intor();
        stu2.intor();
    }
}

三、set()get()下的安全情境

public class Student {
    private String name;
    private int score;

    public void intor() {
        System.out.println("我的名字是" + name + ",我的成绩是" + score + "分。");
    }
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getScore() {
        return score;
    }
    public void setScore(int score) {
        if (score < 0 && score > 100) {
            this.score = 0;
        } else{
            this.score = score;
        }
    }
}
public class TestStudent {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
       Student stu1=new Student();
        Student stu2=new Student();
        stu1.setName("Jack");
        stu2.setName("Fleming");
        stu1.setScore(90);
        stu2.setScore(100);
        stu1.intor();
        stu2.intor();
    }
}

四、使用lombok自动生成set()get()

同样的,为了简便操作,IDEA中我们可以安装lombok插件,使用:

@Getter
@Setter

自动生成set()get()

注意:

  • 应当在每个属性前各使用一次@Getter@Setter
  • 需要一些限制条件时,我们可以通过方法的重写去限定。