C 網路安全教學第 1 卷

封裝冒險

🎮 封裝冒險

透過遊戲學習物件導向程式設計!

經驗值 0/100

等級: 初學者

第 1 級 – 什麼是封裝

封裝的意思是:

  • 在類別中將變數和方法綁定在一起。
  • 將變數設為私有,以保護資料。
  • 透過名為getter和setter的公共方法存取資料。
class Student { private String name ; public void setName (String n) { name = n; } public String getName () { return name; } }

測驗1

為什麼程式設計師要使用封裝?

將所有內容設為公開

保護資料並控制存取

減慢程式速度

Level 2 – Private Variables

Private variables cannot be accessed directly outside the class. Instead:

  • Setter methods update them.
  • Getter methods retrieve them.
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: