C网络安全教程第1卷

封装冒险

🎮 封装冒险

通过游戏学习面向对象编程!

经验值: 0/100

等级: 初学者

第 1 级 – 什么是封装

封装的意思是:

  • 在类中将变量和方法捆绑在一起。
  • 通过将变量设为私有来保护数据。
  • 通过称为 getter 和 setter 的公共方法访问数据。
班级学生{ 私有字符串名称; 公共无效setName(字符串n){ 名称=n; } 公共字符串 getName(){ 返回名称; } }

测验1:

为什么程序员要使用封装?

将所有内容公开

保护数据并控制访问权限

让程序运行变慢

第 2 级 – 私有变量

私有变量无法在类外直接访问。 而是:

  • Setter 方法用于更新它们。
  • Getter 方法用于检索它们。
private int age; public void setAge(int a){ age=a; } public int getAge(){ return age; }

Quiz 2

Which keyword hides variables?

public

private

static

Coding Challenge

Create a setter method called setName.

Final Boss Quiz

Encapsulation combines…

Variables and methods into one class

Loops and arrays

Internet connections

🏆 Congratulations!

You Mastered Encapsulation!

Enter your name: