[Java] 클래스와 객체 2

C____JIN·2022년 6월 15일
0

Java

목록 보기
2/9
post-thumbnail

생성자

생성자란?

public class Person {
	String name;
    float height;
    float weight;
}
public class PersonTest {
	public static void main(String[] args) {
    Person personLee = new Person(); //생성자
}
  • 클래스를 처음 만들 때 상수를 초기화
  • 클래스와 같은 이름의 메서드

디폴트 생성자

public class Person {
	String name;
    float height;
    float weight;
    
    public Person() {} // 디폴트 생성자
}
  • 생성자가 없으면 컴파일러가 자동으로 디폴트 생성자를 제공

생성자 만들기

public class Person {
	String name;
    float height;
    float weight;
    
    public Person() {} // 디폴트 생성자
    
    public Person(String pname) {
    	name = pname;
    }
}
  • 생성자 오버로드
    • 위의 코드의 경우 생성할 때 매개변수로 pname을 받지 않으면 디폴트 생성자
      ex)
      Person person = new Person();
    • 매개변수로 pname을 받으면 Person(String pname)
      ex)
      Person person = new Person("박철진");

참조 자료형

public class Subject {
	String subjectName;
    int scorePoint;
}
public class Student {
	int studentId;
    String studentName;
    
    // Subject 형을 사용하여 선언
    Subject korean;
    Subject math;
}
  • 변수를 추가하지 않아도, Subject 클래스의 멤버 변수 subjectName, scorePoint를 사용할 수 있음
    • 과목 마다 변수를 따로 생성해야되는 번거로움을 줄일 수 있음
  • String도 대표적은 참조 자료형

정보은닉

접근 제어자

접근제어자설명
public외부 클래스 어디에서나 접근 가능
protected같은 패키지 내부와 상속 관계의 클래스에서만 접근 가능
아무것도 없는 경우default이며 같은 패키지 내부에서만 접근 가능
public같은 클래스 내부에서만 접근 가능

get(), set() 메서드

public class Student {
	int studentId;
    private String studentName;
    int grade;
    String address;
    
    public String getStudetName() {
    	return studentName;
    }
    
    public void setStudetName(String studentName) {
    	this.studentName = studentName;
    }
}
public class StudentTest {
	public static void main(String[] args) {
    	Student student = new Student();
        //student.studentName = "박철진";
        
        //setStudentName() 메서드를 활용해 private 변수에 접근 가능
        student.setStudentName("박철진");
        
        System.out.println(student.getStudentName()); // 박철진
    }
}
  • Student 클래스의 studentNameprivate이므로 외부에서 클래스에서 접근 할 수 없음

    • 따라서, 주석처리된 student.studentName = "박철진";은 오류 발생
  • setStudentName 메서드를 통해서 멤버 변수로 접근해서 값 설정

  • getStudentName 메서드를 통해서 멤버 변수로 studentName에 접근

profile
개발 블로그🌐 개발일지💻

0개의 댓글