프로그래밍 언어/Java(연습)
객체 클래스, 접근 제어자
얗마
2016. 5. 3. 20:57
[주제]
- 객체 클래스 사용 방법, 접근 제어자 개념
[중요]
- public: 다른 클래스에서도 사용. 외부에서 접근하여 값 변경도 가능
- private: 현재 정의된 클래스 내에서만 사용
- protected: 동일한 패키지 내에 있는 클래스끼리 사용 가능
- 'this'는 인자로 받는 값과 동일한 이름을 가질 경우 사용
[소스 코딩]
■ Human.java
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 40 41 42 43 44 45 46 47 48 | package classTest; public class Human { /* * [member 변수] * public 설정: 다른 클래스에서도 접근 가능 * private 설정: 은닉성. Human 클래스 내에서만 사용 가능 * - 앞에 범위를 설정안하면 프로젝트 내의 같은 package 내에서만 사용 가능 * final: 상수 개념과 같음. 값이 변할 수 없음 */ private int number; private boolean man; private String address; private final int money = 10; /* * [member method] * this: 0번째 인수 값으로 자기자신을 가리키는 참조. 인수 값에서는 보이지 않음 */ public Human getThis() { return this; } public void setNumber(int n) { number = n; } public int getNumber() { return number; } public boolean isMan() { return man; } public void setMan(boolean man) { this.man = man; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getMoney() { return money; } // public void setMoney(int money) { // this.money = money; // } } | cs |
■ MyClass.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | package classTest; public class MyClass { char c; int x, y; double d; String str; public void method1() { System.out.println("MyClass method1"); } public int method2() { System.out.println("MyClass method2"); return 1; } } | cs |
■ mainClass.java
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 40 41 42 | package classTest; public class mainClass { public static void main(String[] args) { // Human 데이터 int number[] = new int[10]; boolean man[] = new boolean[10]; String address[] = new String[10]; int money[] = new int[10]; number[0] = 1; man[0] = false; address[0] = "서울시"; money[0] = 200000; Human hm = new Human(); // hm == 인스턴스(instance), 객체(object) // Human == class template hm.setNumber(123); int num = hm.getNumber(); System.out.println("num = " + num); Human 홍길동 = new Human(); 홍길동.setNumber(1001); num = 홍길동.getNumber(); System.out.println("num = " + num); MyClass cls = new MyClass(); cls.c = 'A'; cls.x = 15; cls.d = 3.141592; cls.str = "Hi"; cls.method1(); cls.method2(); System.out.println("hm = " + hm); System.out.println("hm.getThis = " + hm.getThis()); } } | cs |
■ 실행결과
■ 첨부 파일