static 키워드.static을 사용.public class Article {
private static int count; // 전체글수
private static String category; // 카테고리
private int num; // 글번호
private String title; // 제목
private String regDate; // 날짜
}
static 변수 할당.new 키워드로 객체, 배열 생성.static 데이터는 데이터 영역에 생성.static 메서드는 동적 메모리의 멤버 변수 사용 불가.static이 아닌 일반 멤버 함수 호출 불가.static 변수는 클래스 단위로 생성되므로 객체 생성과 상관 없이 클래스 이름으로 접근.public class Article {
private static int count; // 전체글수
public static void setCount(int count) {
Article.count = count;
}
public static int getCount() {
return Article.count;
}
}
static을 통한 메모리 효율적 사용과 객체의 생성과 무관한 데이터 공유 가능.
예제 코드
// Article 클래스는 static 변수 count와 일반 변수들을 포함하며,
// Main 클래스에서 static 메서드와 일반 메서드를 통해 각각에 접근하는 예제입니다.
public class Article {
private static int count; // 전체글수
private int num; // 글번호
private String title; // 제목
private String regDate; // 날짜
// static 메서드로 static 변수에 접근하는 예제
public static void setCount(int count) {
Article.count = count;
}
public static int getCount() {
return Article.count;
}
// 일반 메서드로 일반 멤버 변수에 접근하는 예제
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return this.title;
}
}
public class Main {
public static void main(String[] args) {
// static 변수에 접근
Article.setCount(10);
System.out.println("전체 글 수: " + Article.getCount());
// 객체 생성 및 일반 변수에 접근
Article article = new Article();
article.setTitle("제목");
System.out.println("글 제목: " + article.getTitle());
}
}
실행 결과
전체 글 수: 10
글 제목: 제목