Java

[Java] Class 만들기

k_sangmin 2023. 8. 21. 15:05

책 클래스 만들기

1. 멤버 변수 선언

  • 책 이름, 작가, 총 페이지를 멤버변수로 선언
  • private 접근제어 지시자를 이용하여 같은 클래스 내부에서만 접근 가능하게 설계

private String title;

private String author;

private int totalPage;

 

2. 생성자(constructor) 생성

  • 인스턴스와 동시에 멤버변수인 책제목과 작가를 초기화 시키는 생성자 생성

public Book(String title, String author) {

this.title = title;

this.author = author;

}

3. get()/set() 메서드 생성

  • 접근제어지시자 private를 사용하여 멤버 변수를 선언 했기때문에 멤버변수에 접근하기위해 get()/set()메서드 사용

public String getTitle() {

return title;

}

 

public void setTitle(String title) {

this.title = title;

}

 

public String getAuthor() {

return author;

}

 

public void setAuthor(String author) {

this.author = author;

}

 

public int getTotalPage() {

return totalPage;

}

 

public void setTotalPage(int totalPage) {

this.totalPage = totalPage;

}

4. 메서드 생성

  • 책 이름과 작가 정보를 확인할 수 있는 메서드 생성

public void showInfo() {

System.out.println(">>> 책정보 <<< ");

System.out.println("제목 : " + this.title);

System.out.println("작가 : " + this.author);

System.out.println("전체 페이지 수 : " + this.totalPage);

}