์๋ฐ๋ ํด๋์ค์ ๋ฉค๋ฒ ๊ฐ๊ฐ์ ์ธ๋ถ์์ ์ ๊ทผํ ์ ์๋ ๋ฒ์๋ฅผ ์ง์ ํ๋ ์ ๊ทผ ์ง์ ์(์ ๊ทผ์ ์ด์)๋ฅผ ์ค์ ํ ์ ์๋ค.
public
๊ณต๊ฐ ์์ค์ด ์ ์ผ ๋๋ค.
private
๋์ผ ํด๋์ค ๋ด์์๋ง ์ ๊ทผ์ด ๊ฐ๋ฅํจ.
๊ณต๊ฐ์์ค์ด ์ ์ผ ๋ฎ๋ค.
protected
๊ฐ์ ํจํค์ง ๋ด์์ ์ ๊ทผ์ด ๊ฐ๋ฅ.
๋ค๋ฅธ ํจํค์ง์์๋ ์์์ ๋ฐ์ ํด๋์ค ๋ด๋ถ์์ ์ฌ์ฉ๊ฐ๋ฅ.
public๊ณผ ๋ค๋ฅธ ์ ์ ๋ค๋ฅธ ํจํค์ง์ ์์ ํด๋์ค ์ธ๋ถ์์๋ ์ ๊ทผํ ์ ์๋ค๋ ๊ฒ์ด๋ค.
(์ ์ฐ์ง์์)
default (package private)
๊ฐ์ ํจํค์ง ๋ด์์๋ง ์ ๊ทผ์ด ๊ฐ๋ฅํ๋ค.
์ ๊ทผ ์ง์ ์ ๋ฏธ ์ค์ ์ ์๋์ ์ฉ๋๋ ํญ๋ชฉ
์์
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
package main;
import my.MyClass;
public class MainClass {
public static void main(String[] args) {
MyClass cls = new MyClass();
cls.name = "ํ๊ธธ๋";
//public -> ์ ๊ทผ๊ฐ๋ฅ
//cls.number = 1; private -> ์ ๊ทผ ๋ถ๊ฐ๋ฅ
//cls.height = 172.1; protected
cls.setNumber(123);
int number = cls.getNumber();
}
}
|
cs |
========================================================================================================================================================
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
|
package my;
public class MyClass {
/*
Encapsulation == ์๋์ฑ, ์บก์ํ
์ธ๋ถ์ ๊ทผ ์ ์ด(์ฐจ๋จ, ์ฝ๊ธฐ์ ์ฉ, ํ์ฉ์ฌ๋ถ)
์ ๊ทผ์ง์ ์
private : ๊ฐ์ธ์ ์ธ
public: ๋์ค์ ์ธ //์ธ๋ถ์์ ํ์ฉ์ด ๊ฐ๋ฅํ๋ค.
protected: ๋ณดํธ(์์์ ๊ด๋ จ)
*/
// ๋ฉค๋ฒ ๋ณ์๋ 90% private์ผ๋ก ์ด๋ฃจ์ด์ง
private int number; //MyClass์๊ธฐ ๊ตฌ์ญ์์๋ง ์คํ๋.
public String name; // ์ธ๋ถ์์๋ ์ฌ์ฉ์ด ๊ฐ๋ฅ.
protected double height;
//method๋ฅผ ํตํด์ ์ ๊ทผ์ฌ๋ถ ๊ฒฐ์ ํ๋ค.
//์ธ๋ถ์ ํตํ๊ฒ ๋ง๋ค์ด์ฃผ๋ ๊ฒ์
public void setNumber(int number) {//setter
this.number = number;
}
public int getNumber() {//getter
return number;
}
}
|
cs |
'๐ ์๋ฐ Java' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
์์๊ณผ ๋ถ๋ชจํด๋์ค ์์ํด๋์ค (0) | 2021.02.01 |
---|---|
์๋ฐ(JAVA)- ๊ฐ์ฒด์งํฅ ํ๋ก๊ทธ๋จ์ด๋? (0) | 2021.02.01 |
์๋ฐ(JAVA) - this ์ ์๋ฏธ์ ์ฌ์ฉ๋ฒ (0) | 2021.01.27 |
์๋ฐ(JAVA) - ์ด๊ธฐํ์ ์์ฑ์ Constructor (0) | 2021.01.27 |
์๋ฐ(JAVA) - ๋ ์ฃผ์ฌ์ ํฉ ๋ง์ถ๊ธฐ, ๋ฒ ํ ๊ฒ์ (0) | 2021.01.26 |
๋๊ธ