// 하나의 게시물을 표현하기 위한 클래스
public class Article {
private int count; // 전체 글 수
private String category; //카테고리
private String num; // 글 번호
private String title; // 제목
private String regDate; // 날짜
}
-static이 붙은 멤버 변수는 객체의 개수에 상관없이 단 하나만 생성, 이를 모든 객체가 공유하기 때문에 멤로리를 효율적으로 사용할 수 있음
package Static;
public class Article {
// 전체 게시물의 수를 표현하기 위한 데이터
private static int count = 0;
// 모든 게시물은 하나의 카테고리 안에 존재한다고 가정
// 게시물의 분류를 구별하기 위한 데이터
private static String cateory;
private int num; // 글 번호
private String title; // 제목
private String regDate; //작성 일시
public Article(int num, String title, String regDate) {
super();
this.num = num;
this.title = title;
this.regDate = regDate;
// 이 클래스에 대한 객체 생성 -> 게시물 신규 등록
// 게시물이 새로 등록될 떄 마다, 전체 글 수를 의마하는 count 변수가 1씩 증가
// 전체 게시물 수는 모든 객체가 고융하는 값이미로, static으로 선언이 되어야함
count++;
}
public static int getCount() {
return count;
}
public static void setCount(int count) {
Article.count = count;
}
public static String getCateory() {
return cateory;
}
public static void setCateory(String cateory) {
Article.cateory = cateory;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getRegDate() {
return regDate;
}
public void setRegDate(String regDate) {
this.regDate = regDate;
}
@Override
public String toString() {
return "글 분류 = " + cateory + ", 전체 글 수 = " + count + ", Article [num=" + num + ", title=" + title + ", regDate=" + regDate + "]";
}
}
package Static;
public class Main01 {
public static void main(String[] args) {
Article.setCateory("자유게시판");
Article a1 = new Article(1, "1번글", "2024-07-20");
Article a2 = new Article(2, "2번글", "2024-07-21");
Article a3 = new Article(3, "3번글", "2024-07-22");
System.out.println(a1.toString());
System.out.println(a2.toString());
System.out.println(a3.toString());
System.out.println("----------------------");
// static 변수의 값을 변경하면, 모든 객체가 영향을 받음
Article.setCateory("공지사항");
System.out.println(a1.toString());
System.out.println(a2.toString());
System.out.println(a3.toString());
}
}