📚 Static 이란?
static
키워드는 모든 객체가 함께 사용하는 변수
나 메서드
를 만들 때 사용됩니다.객체(인스턴스)
를 만들지 않아도 클래스 이름만으로 바로 사용할 수 있습니다.static
변수와 메서드는 한 번만 생성되고 Method Area(메서드 영역)
에 저장됩니다.💡 static 키워드를 활용해 봅시다.
static
키워드는 변수, 메서드에 붙일 수 있습니다.static
키워드로 선언된 변수와 메서드는 Method Area 에 저장됩니다.class Person {
// ✅ static 변수
static int population = 0;
// ✅ static 메서드
static void printPopulation() {
System.out.println("현재 인구 수: " + population);
}
}
System.out.println("static 변수: " + Person.population);
System.out.println("static 메서드: " + Person.printPopulation);
📚 인스턴스 멤버란?
변수
와 메서드
입니다.Heap
영역에 위치합니다.📚 인스턴스 변수를 알아봅시다.
name
변수는 각 객체마다 별도로 저장됩니다.class Person {
String name; // ✅ 인스턴스 변수
}
public class Main {
public static void main(String[] args) {
Person p1 = new Person(); // p1 객체 생성
p1.name = "gygim"; // ✅ p1 객체의 데이터에 접근
Person p2 = new Person(); // p2 객체 생성
p2.name = "Steve"; // ✅ p2 객체의 데이터에 접근
}
}
📚 인스턴스 메서드를 알아봅시다.
class Person {
String name;
void printName() { // ✅ 인스턴스 메서드
System.out.println("나의 이름은 " + this.name + "입니다.");
}
}
public class Main {
public static void main(String[] args) {
Person p1 = new Person();
p1.name = "gygim";
p1.printName(); // ✅ p1 객체의 메서드 실행
Person p2 = new Person();
p2.name = "Steve";
p2.printName(); // ✅ p2 객체의 메서드 실행
}
}
📚 클래스 멤버를 알아봅시다.
변수
와 메서드
를 의미합니다.static
키워드를 사용해서 선언합니다.Method Area
에 적재됩니다.📚 클래스 변수를 알아봅시다.
Heap
이 아니라 Method Area
에 저장됩니다.클래스명.변수명
으로 접근 가능합니다.class Person {
static int population = 0; // ✅ 클래스 변수
}
public class Main {
public static void main(String[] args) {
System.out.println("현재 인구 수: " + Person.population);
Person p1 = new Person();
Person p2 = new Person();
System.out.println("현재 인구 수: " + Person.population);
}
}
📚 클래스 메서드를 알아봅시다.
class Person {
static int population = 0;
public Person(String name) {
this.name = name;
population++; // 생성자 호출 시 population 1 증가
}
static void printPopulation() {
System.out.println("현재 인구 수: " + population); // ✅ 클래스 메서드
}
}
public class Main {
public static void main(String[] args) {
Person.printPopulation(); // 현재 인구 수: 0
Person p1 = new Person("gygim");
Person p2 = new Person("Steve");
Person.printPopulation(); // 현재 인구 수: 2
}
}
⚠️ 클래스 변수 사용 시 주의 사항
public class Student {
static String name; // ⚠️ 모든 객체가 동일한 name을 공유 (위험)
public Student(String name) {
this.name = name;
}
public void printName() {
System.out.println("이름: " + name);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("gygim");
Student s2 = new Student("Steve");
s1.printName(); // ⚠️ "이름: Steve"
s2.printName(); // ⚠️ "이름: Steve"
}
}
⚠️ static
변수는 꼭 필요할 때만 사용해야 합니다. 프로그램이 종료될 때까지 메모리에 유지되므로 남용하면 메모리 낭비로 이어질 수 있습니다.