知识库 知识库
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)

Jim FuckPPT

Java小学生
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)
  • Hyperskill - Java

    • Java basic

    • Java OOP

      • Theory:Introduction OOP
      • Theory:Defining classes
      • Theory:Instance methods
      • Thoery:Constructor
      • Theory:Package
      • Theory:Access modifiers
      • Theory:Getters and setters
        • Data encapsulation
        • Getters and setters
        • Conclusion
      • Theory:Inheritance
      • Theory:Protected modifier
      • Theory:Referencing subclass objects
      • Theory:The Object class
      • Theory:Objects
      • Theory:Interface
      • Theory:Multiple constructors
      • Theory:The keyword super
      • Theory:Static members
      • Theory:Hiding and overriding
      • Theory:Polymorphism
      • Theory:Abstract class
      • Theory:Abstract class vs interface
      • Theory:Anonymous classes
      • Theory:Anonymous classes properties
    • 应知

    • 扩展

    • IO & Stream

    • Error & Exception

    • Algorithm & Data structure

    • Design pattern

    • Web

    • Spring boot

  • 练习题

  • Frank - Java与生活

  • Frank - Java API进阶

  • 学习笔记

  • Java
  • Hyperskill - Java
  • Java OOP
Jim
2022-05-09
目录

Theory:Getters and setters

# Data encapsulation

According to the data encapsulation principle, the fields of a class cannot be directly accessed from other classes. The fields can be accessed only through the methods of that particular class.

To access hidden fields, programmers write special types of methods: getters and setters. Getters can only read fields, and setters can only write (modify) the fields. Both types of methods should be public.

Using these methods gives us some advantages:

  • the fields of a class can be made read-only, write-only, or both;
  • a class can have total control over what values are stored in the fields;
  • users of a class don't know how the class stores its data and don't depend on the fields.

# Getters and setters

Java doesn't provide any special keywords for getter and setter methods. Their main difference from other methods is their names.

According to the JavaBeans Convention (opens new window):

  • getters start with get, followed by the variable name, with the first letter of the variable name capitalized;
  • setters start with set, followed by the variable name, with the first letter of the variable name capitalized.

This convention applies to any types except boolean. A getter for a boolean field starts with is, followed by the variable name.

Example 1. The class Account has four fields: id, code, balance and enabled. Each field has a keyword private to hide the field from direct access from other classes. Also, the class has public getters and setters for accessing fields through these methods.

class Account {

    private long id;
    private String code;
    private long balance;
    private boolean enabled;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public long getBalance() {
        return balance;
    }

    public void setBalance(long balance) {
        this.balance = balance;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

Here you can see the different getters and setters for the class Account. Just as the convention states, the boolean field enabled has a different getter name: it starts with the word is instead of get.

Let's create an instance of the class and fill the fields, then read values from the fields and output them.

Account account = new Account();

account.setId(1000);
account.setCode("62968503812");
account.setBalance(100_000_000);
account.setEnabled(true);

System.out.println(account.getId());      // 1000
System.out.println(account.getCode());    // 62968503812
System.out.println(account.getBalance()); // 100000000
System.out.println(account.isEnabled());  // true
1
2
3
4
5
6
7
8
9
10
11

Sometimes, getters or setters can contain a more sophisticated logic. For example, g****etters may return non-stored values (calculated at runtime), or setters may also in some cases modify the value of another field according to changes. But usually, getters and setters have a minimum of programming logic.

Example 2. In the following class, the setter setName doesn't change the current value if the passed value is null.

class Patient {

    private String name;

    public Patient(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }
    
    public void setName(String name) {
        if (name != null) {
            this.name = name;
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# Conclusion

To restrict access to fields from external code make them private and write suitable getters/setters to read/change only the fields you need. Do not forget to make use of the naming convention when writing them.

提示

Note, modern IDEs (such as IntelliJ IDEA) can generate getters and setters automatically based on class fields.

编辑 (opens new window)
#Java#OOP
上次更新: 2022/09/26, 16:55:15
Theory:Access modifiers
Theory:Inheritance

← Theory:Access modifiers Theory:Inheritance→

最近更新
01
《挪威的森林》
04-14
02
青钢影
04-14
03
Processing strings
02-18
更多文章>
Theme by Vdoing | Copyright © 2022-2023 Jim Frank | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式