클래스(class)의 구성요소

이정연·2023년 6월 26일

자바기초

목록 보기
14/25

구성요소

  • 클래스는 4가지 구성요소로 이루어 진다.
  • 필드, 메서드, 생성자, 이너클래스이다.
public class ExampleClass {
	int x = 10; // (1)필드
	void printX() {...} // (2)메서드
	ExampleClass {...} // (3)생성자
	class ExampleClass2 {...} // (4)이너 클래스
} 
  • 필드 : 클래스의 속성
  • 메서드 : 클래스의 기능
  • 생성자 : 클래스의 객체를 생성하는 역할
  • 이너클래스 : 클래스 내부의 클래스

필드

  • 클래스의 필드에는 3가지가 있다.
  • 클래스변수, 인스턴스변수, 지역변수
class Example { // => 클래스 영역
	int instanceVariable; // 인스턴스 변수
	static int classVariable; // 클래스 변수(static 변수, 공유변수)

	void method() { // => 메서드 영역
		int localVariable = 0; // 지역 변수. {}블록 안에서만 유효
	}
}
  • 인스턴스변수와 클래스변수는 static 키워드의 유무로 구분할 수 있다.
  • 지역변수는 메서드 내에 선언되고 메서드 내에서만 사용 가능하다.

✨인스턴스 변수

  • 인스턴스 변수는 인스턴스가 가지는 각각의 고유한 속성을 저장하기 위한 변수로 new 생성자() 로 인스턴스가 생성될 때 만들어진다.
  • 클래스를 통해 만들어진 인스턴스는 힙 메모리의 독립적인 공간에 저장된다.
public class CarTest {
    public static void main(String[] args) {
        Car tesla = new Car("3", "red"); // 아래 인스턴스 변수에 대한 객체 생성
        System.out.println("내 차의 모델은 " + tesla.model + "이고 " + "색은 " + tesla.color + "입니다."); // 필드 호출
    }
}

class Car { //클래스
    public String model; // 필드 선언, 인스턴스 변수
    public String color;

    public Car(String model, String color) { // 인스턴스 초기화를 위한 생성자 함수. 이후 챕터에서 학습 예정.
        this.model = model;
        this.color = color;
    }


// 출력값
내 차의 모델은 3이고 색은 red입니다.

✨클래스 변수

  • 공통된 저장공간을 공유한다.
  • 한 클래스로부터 생성되는 모든 인스턴스가 특정한 값을 공유해야 하는 경우에 static 키워드를 사용하여 클래스 변수를 선언하게된다.
  • 사람을 예로들면 손가락과 발가락 개수와 같이 모든 사람이 공유하는 특성같은 것들이다.
  • 클래스 변수는 인스턴수 변수와 달리 인스턴스를 따로 생성하지 않고도 언제라도 (클래스명).(클래스변수명) 을 통해 사용이 가능하다.
  • 이것은 메모리 구조에서 메서드 처럼 클래스 영영에저장되어 그 값을 공유하기 때문이다.
public class CarTest {
    public static void main(String[] args) {

        System.out.println("내 차의 모델은 " + Car.model + "이고 " + "색은 " + Car.color + "입니다."); // 필드 호출        
    }
}

class Car {
    public String model = "3"; // 필드 선언
    public String color = "red";
}

//출력값
내 차의 모델은 3이고 색은 red입니다.

클래스변수 에시

public class StaticFieldTest {
    public static void main(String[] args) {
        StaticField staticField1 = new StaticField(); // 객체 생성
        StaticField staticField2 = new StaticField();

        staticField1.num1 = 100; 
        staticField2.num1 = 1000;

        System.out.println(staticField1.num1);
        System.out.println(staticField2.num1);

        staticField1.num2 = 150;
        staticField2.num2 = 1500;
        System.out.println(staticField1.num2);
        System.out.println(staticField2.num2);

    }
}

class StaticField {
    int num1 = 10;
    static int num2 = 15;
}

//출력값
100
1000
1500
1500
  • num1의 경우에 각각 staticField1.num1 = 100;, staticField2.num1 = 1000;으로 따로 독립적으로 지정을 해주고있다. 이 값들은 인스턴스 필드이기때문에 staticField1,staticField2에 각각 저장이되어서 호출을 했을 때 각각 100, 1000으로 나오는것을 알 수 있다.
  • 하지만, num2의 경우에 staticField1.num2 = 150;, staticField2.num2 = 1500; 로 선언해주면
    • staticField1.num2 = 150;에서 StaticField의 num2 값은 150이된다.
    • 이어서 staticField2.num2 = 1500;를 해주면 어떤 일이 일어날까 StaticField의 num2값은 static이기 때문에 고정된 값이기에 150에서 1500으로 바뀌게된다. 결국 staticField1이나 staticField2나 다른객체긴하지만, 같은 클래스인 StaticField에서 생성되기 때문에 클래스변수인 num2를 공유하게 된다.
    • 따라서 가장 최근에 선언된 값인 1500이 출력된다.

✨지역변수

  • 메서드내에 선언되며 메서드 내에서만 사용
  • 스택 메모리에 저장된다.
  • 메서드가 종료되는것과 종시에 함께 소멸되어 더이상 사용할 수 없음
  • 스택메모리에 저장되는 지역변수는 한동안 사용되지 않으면 가상머신에 의해 자동으로 삭제
  • 지역변수는 다른변수와 다르게 반드시 초기화를 실행해줘야한다.
profile
반갑습니다.

0개의 댓글