본문 바로가기
Java

2-4 클래스와 객체1 (4) - 참조 자료형, private

by yukuda 2024. 3. 14.
728x90

참조 자료형

변수의 자료형 - 기본 자료형 ( int, long, float, double 등)

                        - 참조 자료형 ( String, Date, Student 등) (클래스가 자료형이 되는거죠)

package refernence;

public class Circle {
	Point point;
	int radius;

	public Circle() {
		point = new Point();
	}
}
package refernence;

public class Point {
	int x;
	int y;
}

참조 자료형의 예

학생의 속성 중 수업에 대한 부분

수업에 대한 각 속성을 학생 클래스에서 정의 하지 않고 수업이라는 클래스로 분리해서 사용

이때 과목은 참조 자료형으로 선언

과목이랑 학생을 분리

package reference;

public class Student {
	int studentID;
	String studentName;

	Subject korea;
	Subject math;

	public Student() {
		korea = new Subject("국어");
		math = new Subject("수학");
	}

	public Student(int id, String name) {
		studentId = id;
		studentName = name;

		korea = new Subject("국어");
		math = new Subject("수학");
	}

	public void setKorea(int score){
		korea.setScore(score);		
	}

	public void setMath(int score){
		math.setScore(score);
	}

	public void showStudentInfo() {
		int total = korea.getScore() + math.getScore();
		sysout(studentName + " 학생의 총점은 "+ total + "입니다.");

}

package reference;

public class Subject {
	String subjectName;
	int score;

	public Subject(String name) {
		subjectName = name;
	}
	public void setSubjectName(String name){
		subjectName = name;
	}
	public int getScore() {
		return score;
	}
	public void setScore(int score) {
		this.score = score;
	}
	public String getSubjectName() {
		return subjectName;
	}
}
package reference;

public class StudentTest {
	public static void main(String[] args) {
		Student studentJames = new Student(100, "James");
		studentJames.setKorea(100);
		studentJames.setMath(100);

		Student studentTomas = new Student(101, "Tomas");
		studentTomas.setKorea(80);
		studentTomas.setMath(60);

		studentJames.showStudentInfo();
		studentTomas.showStudentInfo();
	}
}

정보은닉

private 접근 제어자

클래스의 외부에서 클래스 내부의 멤버 변수나 메서드에 접근(access)하지 못하게 하는 경우 사용

멤버 변수나 메서드를 외부에서 사용하지 못하도록 하여 오류를 줄일 수 있음

변수에 대해서는 필요한 경우 get(), set() 메서드를 제공

package hiding;

class BirthDay {
	private int day;
	private int month;
	private int year;

	public int getDay(){
		return day;
	}

	public void setDay(int day) {
	if(month == 2){
			if( day <1 || day >28){
				sysout("날짜 오류입니다.");
			}
	}else{
		this.day = day;
	}
	}

	public int getMonth(){
		return month;
	}

	public void setMonth(int month) {
		this.month = month;
	}

	public int getYear(){
		return year;
	}

	public void setYear(int year) {
		this.year = year;
	}

}
public class BirthDayTest{
	public static void main(String[] args) {

		BirthDay day = new BirthDay();
		day.setMonth(2);	
		day.setDay(30);
		day.setYear(2018);
}