Languages/Java
[JAVA]JAVA 생성자,참조자료형,정보은닉
환테크
2021. 2. 18. 17:07
반응형
생성자
인스턴스 생성 시 new키워드와 함꼐 사용했던 생성자
디폴트 생성자(dafault constructor)
하나의 클래스에는 반드시 적어도 하나 이상의 constructor가 존재
프로그래머가 constructor 를 기술하지 않으면 default
constructor가 자동으로 생김 (컴파일러가 코드에 넣어줌)
default constructor 는 매게 변수가 없음
default constructor 는 구현부가 없음
만약 클래스에 매개변수가 있는 생성자를 추가하면 디폴트 생성자는
제공되지 않음
참조자료형
변수의 자료형
기본자료형 int, long,double, ...
참조 자료형 String,Date,Student,...
클래스 형으로 선언하는 자료형
예
학생의 속성 중 수업에 대한 부분
수업에 대한 각 속성을 학생 클래스에 정의 하지 않고
수업이라는 클래스로 분리해서 사용
이때 과목은 참조 자료형으로 선언
package classpart;
public class Student {
int studentID;
String studentName;
int grade;
String address;
//public student() {} 가 생성자 (생략가능)
public Student() {}//but new생성자를 만들경우에는 불가능
public Student(int id,String name) {
studentID = id;
studentName = name;//생성자를 직접 만들었다
}
public void showStudentInfor() {
System.out.println(studentName + "," + studentID);
}
public String getStudentName() {
return studentName;
}
public void setStudentname(String name) {
studentName = name;
}
public static void main(String[] args) {
Student studentLee = new Student();
studentLee./*참조변수*/studentName = "이순신";
studentLee.studentID = 100;
Student studentKim = new Student();
studentKim./*참조변수*/studentName = "김순신";
studentKim.studentID = 101;
studentLee.showStudentInfor();
studentKim.showStudentInfor();
}
}
student 생성자를 사용한 것을 확인
package classpart;
public class StudentTest {
public static void main(String[] args) {
Student studentLee = new Student();
studentLee./*참조변수*/studentName = "이순신";
studentLee.studentID = 100;
Student studentKim = new Student();
studentKim./*참조변수*/studentName = "김순신";
studentKim.studentID = 101;
studentLee.showStudentInfor();
studentKim.showStudentInfor();
System.out.println(studentLee);
System.out.println(studentKim);
}
}
정보은닉
private 접근 제어자
클래스의 외부에서 클래스 내부의 멤버 변수나 메서드에
접근 하지 못하게 사용
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)
System.out.println("날짜 오류입니다.");
}
}
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.setDay(30);
day.setMonth(2);
day.setYear(2018);
}
}
용어정리
객체 : 객체 지향 프로그램의 대상 생성된 인스턴스
클래스 : 객체를 프로그래밍하기 위해 코드로 만든 상태
인스턴스 : 클래스가 메모리에 생성된 상태
멤버 변수 : 클래스의 속성,특성
메서드 : 멤버 변수를 이용하여 클래스의 기능을 구현
참조변수 : 메모리의 생선된 인스턴스를 가리키는 변수
참조값 : 생성된 인스턴스의 메모리 주소 값
반응형