[Java] Static

이다혜·2023년 10월 23일
0

Java

목록 보기
2/23
post-thumbnail

static : '정적인, 고정된'이라는 뜻으로
어떤 객체에 소속되는 것이 아닌, 클래스에 고정되어 있는 변수나 메서드

1. 인스턴스 변수

int maxSpeed를 인스턴스 변수로 만들면 각각의 객체가 하나씩 age를 가집니다.

lass Person {
  int maxSpeed;
}

Person p1 = new Person();
p1.maxSpeed = 100;
Person p2 = new Person();
p2.maxSpeed = 200;
Person p3 = new Person();
p3.maxSpeed = 300;

System.out.println(p1.maxSpeed); // 100
System.out.println(p2.maxSpeed); // 200
System.out.println(p3.maxSpeed); // 300

2. static 변수

ing maxSpeed를 static 변수로 만들면 오직 클래스가 변수를 가집니다.

class Person {
    static int maxSpeed;
}

Person p1 = new Person();
p1.maxSpeed = 100; // 이 코드는 실질적으로 `Person.maxSpeed = 100;` 으로 처리된다. 왜냐하면 p1 객체에는 maxSpeed 변수가 없고, maxSpeed 변수는 클래스에 1개만 존재하기 때문이다.
Person p2 = new Person();
p2.maxSpeed = 200;
Person p3 = new Person();
p3.maxSpeed = 300;

System.out.println(p1.maxSpeed); // 300 // 이 코드는 실질적으로 `System.out.println(Person.maxSpeed);` 와 같다.
System.out.println(p2.maxSpeed); // 300
System.out.println(p3.maxSpeed); // 300

❓ 왜 static이 필요할까?

  1. 각각의 객체가 가질 필요 없는 변수는 static을 붙여서 용량을 절약할 수 있습니다.
  2. 객체.변수가 아닌 클래스.변수와 같은 방식으로 접근할 수 있어서 객체화가 필요 없습니다.

0개의 댓글