-
728x90๋ฐ์ํ
Encapsulation ( ์บก์ํ )
<1>์ ํ์
- ์ ํ์ (modifier) ํด๋์ค, ๋ณ์, ๋ฉ์๋ ์ ์ธ๋ถ์ ํจ๊ผ ์ฌ์ฉ๋์ด ๋ถ๊ฐ์ ์ธ ์๋ฏธ๋ฅผ ๋ถ์ฌ
- ์ ๊ทผ ์ ํ์ : private, default(package), protected, public
- static : ํด๋์ค ๋ ๋ฒจ์ ์์ ์ค์
- final : ์์๋ฅผ ๋์ด์ ์์ ํ ์ ์๊ฒ ํจ
- abstract: ์ถ์ ๋ฉ์๋ ๋ฐ ์ถ์ ํด๋์ค ์์ฑ
- synchronized: ๋ฉํฐ ์ค๋ ๋์์์ ๋๊ธฐํ ์ฒ๋ฆฌ
- ์ ๊ทผ ์ ํ์
public class Parent{public int publicVar;protected int protectedVar;int defaultVar;private int privVar;public void useMember(){this.publicVar=10; this.protectedVa= 10;this.defaultVar=10;this.privVar 10;}}public class Child extends Parent{public void useMember(){this.publicVar = 10;this.protectVar =10;this.defaultVar=10; //๊ฐ๋ฅthis.privVar =10 ;this.some = 10; //๋ถ๊ฐ๋ฅ}}public class Friend {public void method(){p.publicVar=1;p.protectVar=1;p.defaultVar =1; //๊ฐ๋ฅp.privVar=1; //not visible}}๐งธ ํ๋์ ๋์์ ์ฌ๋ฌ ์ ํ์๋ฅผ ์กฐํฉ ๊ฐ๋ฅํ๋, ์ ๊ทผ ์ ํ์๋ ํ๋๋ง ์ฌ์ฉ ๊ฐ๋ฅํ๋ค โ Eclipse ๋ฅผ ์ด์ด๋ณด๋ฉด, class ์์ฑ ์ modifiers๋์ ๋ณด๋ฉด ์ ๊ทผ์ ํ์๋ radio button์ผ๋ก ํ๋๋ง ์ค์ ํ ์ ์์ง๋ง, abstract๋ final ์ ์ค๋ณต ์ ํ ๊ฐ๋ฅํ ๊ฒ์ ํ์ธํด๋ณผ ์ ์๋ค.
๐งธ ์์๋ ๋ฌด๊ดํ๋ ์ผ๋ฐ์ ์ผ๋ก ์ ๊ทผ ์ ํ์๋ฅผ ๋งจ ์์ผ๋ก ์ฌ์ฉํ๋ค
๐งธ final ์ฉ๋ :
- final class: ๋์ด์ ํ์ฅ ํ ์ ์์ - ์์ ๊ธ์ง โ ์ค๋ฒ๋ผ์ด๋๋ฅผ ๋ฐฉ์ง (์ด๋ฏธ ์๋ฒฝ^^)
- final method: ๋์ด์ ์ฌ์ ์ ๋ถ๊ฐ โ ์ค๋ฒ๋ผ์ด๋ฉ ๊ธ์ง
- final variable: ๋์ด์ ๊ฐ์ ๋ฐ๊ฟ ์ ์์ โ ์์ํ
<2>์บก์ํ
๐คฆ๐ปโโ๏ธ Eclipse > Source ๋ค์ด๊ฐ๋ฉด constructors, getters and setters ๋ฅผ ์๋์ผ๋ก ์์ฑํด์ค๋ค !
๋ฐ์ดํฐ ์๋๊ณผ ๋ณดํธ
์ธ๋ถ์์ ๋ณ์๋ฅผ ์ง์ ์ ๊ทผํ๋ค๋ฉด ์์คํ ์ ๋ณด๊ฐ ๋ณดํธ๋์ง ๋ชปํ๋ค. ๋ฐ๋ผ์, ๋ณ์๋ฅผ private ์ ๊ทผ์ผ๋ก ๋ง๊ณ ๊ณต๊ฐ๋๋ ๋ฉ์๋๋ฅผ ํตํด ์ ๊ทผ ํต๋ก๋ฅผ ๋ฐ๋ก ๋ง๋ จํด์ค๋ค (Setters & Getters)
<3>์ฑ๊ธํด ๋์์ธ ํจํด
- ๊ฐ์ฒด์ ์์ฑ์ ์ ํํด์ผ ํ๋ ๊ฒฝ์ฐ
- ์ฌ๋ฌ๊ฐ์ ๊ฐ์ฒด๊ฐ ํ์ ์๋ ๊ฒฝ์ฐ: ์์ ๊ฐ๋ฅํ ๋งด๋ฒ๋ณ์๊ฐ ์๊ณ ๊ธฐ๋ฅ๋ง ์๋ ๊ฒฝ์ฐ (stateless)
- ๊ฐ์ฒด๋ฅผ ๊ณ์ ์์ฑ/ ์ญ์ ํ๋๋ฐ ๋ง์ ๋น์ฉ์ด ๋ค์ด์ ์ฌ์ฌ์ฉ์ด ์ ๋ฆฌํ ๊ฒฝ์ฐ
- ์ฑ๊ธํด ๋์์ธ ํจํด
- ์์ฑ์์ ์ ๊ทผ ์ ํ์๋ฅผ private์ผ๋ก ์ค์ ํ์ฌ ์ธ๋ถ์์ ์์ฑ์์ ์ ๊ทผ ๊ธ์ง
- ๋ด๋ถ์์๋ private์ ์ ๊ทผ ๊ฐ๋ฅํ๋ฏ๋ก ์ง์ ๊ฐ์ฒด ์์ฑ โ ๋งด๋ฒ ๋ณ์์ด๋ฏ๋ก private
- Getter ์์ฑ : ์ธ๋ถ์์ private member์ ์ ๊ทผ ๊ฐ๋ฅํ๊ฒ ํจ(setter๋ ํ์x)
- Getter ์ ๋ณ์์ static์ ์ถ๊ฐํ์ฌ ๊ฐ์ฒด ์์ด ์ธ๋ถ์์ ์ ๊ทผํ ์ ์๋๋ก ํจ
๐งธ ์ธ๋ถ์์ getter ์ ํตํด์ ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํ๊ธฐ๋๋ฌธ์ ํ๋์ ๊ฐ์ฒด๋ง ์ฌ์ฌ์ฉํ ์์๋ค
728x90๋ฐ์ํ - ์ ํ์ (modifier) ํด๋์ค, ๋ณ์, ๋ฉ์๋ ์ ์ธ๋ถ์ ํจ๊ผ ์ฌ์ฉ๋์ด ๋ถ๊ฐ์ ์ธ ์๋ฏธ๋ฅผ ๋ถ์ฌ