Java
[Java] 접근지정자 - private / getter, setter
H'
2021. 7. 17. 12:07
> private 접근지정자
클래스 안의 멤버(필드, 메서드)를 private 으로 선언하면
해당 클래스 내부에서만 접근, 참조가 가능하다.
다른 클래스에서 참조하려고 하면 is not visiblr 접근지정자가 접근하지 못했다는 오류 발생
> private 선언된 필드에 접근하는 방법
1. public int a; 필드의 접근지정자를 public 으로 수정한다. (이럴거면 처음부터 public 했겠지?)
2. private 필드에 접근할 수 있는 public 메서드를 선언하는 방법 ***
우클릭+source 클릭해서 (단축키 : alt + shift + s) getter, setter (get(), set()) 함수 선언
MyPoint.java
package days16;
// x,y 좌표점를 관리하는 유용한 필드, 메서드를 구현한 클래스
// [private 멤버 변수가 접근 가능한 같은 클래스]
public class MyPoint {
// fields 속성
public int x;
int y;
// 생성자 오버로딩 가능
// 디폴트 생성자 [함수] 선언
public MyPoint() {
System.out.println("> MyPoint Default Constructor..");
}
public MyPoint(int i) {
x = i;
y = i;
System.out.println("> MyPoint 1 Constructor..");
}
public MyPoint(int i, int j) {
x = i;
y = j;
System.out.println("> MyPoint 2 Constructor..");
}
/* == public int z;
private int z;
// getter, setter 선언
public int getZ() {
return z; //읽기
}
public void setZ(int value) {
z = value; //쓰기
}
*/
// method 기능
public void pointOffSet(int n) //함수 원형, 프로토타입(prototype) 선언부
{ //함수 몸체 ./, 구현부
x += n;
y += n;
}
// p1.dispPoint()
// p2.dispPoint()
public void dispPoint() {
System.out.printf("> x=%d, y=%d\n", x, y);
}
// 리턴 자료형, 매개변수 자료형으로 [클래스] 올 수 있다구염
// 리턴 자료형 : 클래스 MyPoint
// 매개변수 자료형 : 클래스 MyPoint
// 참조형 반환타입
// p1 MyPoint p = p2
/*
public MyPoint plusPoint(MyPoint p) {
//새로운 MyPoint객체 mp를 생성
MyPoint mp = new MyPoint();
mp.x = x + p.x;
mp.y = y + p.y;
return mp;
}
*/
// p1.plusPoint(p2)
// p1 호출한 객체
public MyPoint plusPoint(MyPoint p) {
MyPoint mp = new MyPoint();
mp.x = this.x + p.x;
mp.y = this.y + p.y;
return this; // ㄷ. this 리턴값으로 사용되는 경우
}
}//class
Ex05.java
package days16;
import days15.Student;
public class Ex05 {
public static void main(String[] args) {
// MyPoint 클래스와 Ex05 클래스는 같은 패키지(days16)
MyPoint p1 = new MyPoint();
p1.x = 10; //public
p1.y = 20; //default(같은 패키지니까)
Student s1 = new Student();
int kor = 101;
s1.setKor(kor);
// 필드 - 읽기전용(getter), 쓰기전용(setter)
// s1.setTot(100); //쓰기작업
// s1.getTot(); //읽기작업
System.out.println(s1.getKor());
}//main
}//class