코딩 스쿨 Java

언어선택 : HTMLCSSJAVAJAVASCRIPTMYSQLSQL PHP

Java Class Attributes

자바 클래스 속성 (Class Attributes): 개념 및 사용법

자바 클래스 속성(Class Attributes)은 클래스 내에서 정의된 변수로, 객체의 상태를 저장하는 데 사용됩니다. 속성은 필드(Field)라고도 하며, 클래스나 객체의 중요한 데이터를 나타냅니다. 이 글에서는 자바 클래스 속성의 종류, 선언 방법, 접근 방법 등을 예제와 함께 설명합니다.

클래스 속성이란?

클래스 속성(필드)은 클래스에서 선언된 변수로, 클래스가 나타내는 객체의 상태를 나타냅니다. 각 객체는 고유한 속성 값을 가질 수 있으며, 이를 통해 객체의 상태를 저장하고 조작할 수 있습니다.

속성의 종류

자바 클래스 속성은 크게 두 가지로 나눌 수 있습니다:

  1. 인스턴스 변수(Instance Variable): 클래스의 각 인스턴스(객체)마다 고유한 값을 가집니다. 객체가 생성될 때마다 새로운 메모리 공간이 할당됩니다.
  2. 클래스 변수(Class Variable, 정적 변수): 모든 객체가 공유하는 하나의 변수입니다. static 키워드를 사용하여 선언하며, 클래스 레벨에서 메모리가 할당됩니다.

1. 인스턴스 변수 (Instance Variables)

인스턴스 변수는 객체마다 독립적인 값을 가집니다. 클래스 내에서 선언되며, 객체가 생성될 때 초기화됩니다.

인스턴스 변수 선언 및 사용 예제

class Car {
    // 인스턴스 변수
    String model;
    String color;
    int year;

    // 생성자
    public Car(String model, String color, int year) {
        this.model = model;
        this.color = color;
        this.year = year;
    }

    // 메서드
    public void displayInfo() {
        System.out.println("Model: " + model);
        System.out.println("Color: " + color);
        System.out.println("Year: " + year);
    }
}

public class Main {
    public static void main(String[] args) {
        // 각 객체가 고유한 속성 값을 가짐
        Car car1 = new Car("Tesla Model S", "Red", 2023);
        Car car2 = new Car("BMW X5", "Black", 2021);

        car1.displayInfo();
        car2.displayInfo();
    }
}

결과:

Model: Tesla Model S
Color: Red
Year: 2023
Model: BMW X5
Color: Black
Year: 2021

위 예제에서 car1car2는 서로 다른 속성 값을 가집니다. 각 객체의 model, color, year 값은 해당 객체만의 상태를 나타냅니다.

2. 클래스 변수 (Class Variables)

클래스 변수는 객체가 아닌 클래스 자체에 속하는 변수로, 클래스에 속한 모든 객체가 공유합니다. 클래스 변수는 static 키워드를 사용하여 선언되며, 하나의 메모리 공간만 할당됩니다.

클래스 변수 선언 및 사용 예제

class Car {
    // 클래스 변수
    static int numberOfCars = 0;

    // 인스턴스 변수
    String model;
    String color;

    // 생성자
    public Car(String model, String color) {
        this.model = model;
        this.color = color;
        numberOfCars++;  // 객체가 생성될 때마다 카운트 증가
    }

    public void displayInfo() {
        System.out.println("Model: " + model);
        System.out.println("Color: " + color);
    }

    // 클래스 메서드
    public static void displayTotalCars() {
        System.out.println("Total number of cars: " + numberOfCars);
    }
}

public class Main {
    public static void main(String[] args) {
        // 새로운 객체 생성 시 클래스 변수 업데이트
        Car car1 = new Car("Tesla Model S", "Red");
        Car car2 = new Car("BMW X5", "Black");

        // 각 객체의 정보 출력
        car1.displayInfo();
        car2.displayInfo();

        // 클래스 변수 호출
        Car.displayTotalCars();  // 출력: Total number of cars: 2
    }
}

결과:

Model: Tesla Model S
Color: Red
Model: BMW X5
Color: Black
Total number of cars: 2

위 예제에서 numberOfCars는 클래스 변수로, Car 클래스에 속한 모든 객체가 공유합니다. 따라서 car1car2 객체가 생성될 때마다 numberOfCars의 값이 증가합니다. 클래스 변수는 static 메서드 내에서도 접근할 수 있습니다.

속성 접근 제어 (Access Modifiers)

자바에서는 클래스 속성에 접근할 수 있는 범위를 제어하는 접근 제어자를 제공합니다. 주로 사용하는 접근 제어자는 다음과 같습니다:

  • public: 어디서든 접근할 수 있습니다.
  • private: 클래스 내부에서만 접근할 수 있습니다.
  • protected: 동일한 패키지나 상속받은 클래스에서 접근할 수 있습니다.
  • default(아무 것도 명시하지 않음): 동일한 패키지 내에서만 접근할 수 있습니다.

접근 제어자 예제

class Person {
    private String name;   // private: 클래스 내부에서만 접근 가능
    public int age;        // public: 어디서든 접근 가능

    // 생성자
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getter 메서드로 외부에서 name 필드에 접근
    public String getName() {
        return name;
    }

    // Setter 메서드로 외부에서 name 필드 값 수정
    public void setName(String name) {
        this.name = name;
    }
}

public class Main {
    public static void main(String[] args) {
        Person person = new Person("John", 25);

        // private 필드에 직접 접근 불가 (컴파일 오류 발생)
        // person.name = "Jane"; // 오류

        // Getter와 Setter를 통해 접근
        System.out.println(person.getName());  // 출력: John
        person.setName("Jane");
        System.out.println(person.getName());  // 출력: Jane

        // public 필드는 직접 접근 가능
        person.age = 30;
        System.out.println("Age: " + person.age);  // 출력: Age: 30
    }
}

결과:

John
Jane
Age: 30

위 예제에서 name 필드는 private로 선언되어 클래스 외부에서 직접 접근할 수 없습니다. 대신, getName()setName() 메서드를 통해 필드에 접근할 수 있습니다. 반면, age 필드는 public으로 선언되어 객체를 통해 직접 접근할 수 있습니다.

상수 필드 (Final Fields)

클래스 속성에 final 키워드를 붙이면, 그 값은 한 번만 초기화되고 변경할 수 없습니다. 주로 상수(Constant)를 선언할 때 사용됩니다.

상수 필드 예제

class Circle {
    // 상수 필드
    public static final double PI = 3.14159;

    // 인스턴스 변수
    double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double calculateArea() {
        return PI * radius * radius;
    }
}

public class Main {
    public static void main(String[] args) {
        Circle circle = new Circle(5);
        System.out.println("Area: " + circle.calculateArea());  // 출력: Area: 78.53975
    }
}

결과:

Area: 78.53975

위 예제에서 PIfinal로 선언된 상수로, 더 이상 수정할 수 없는 값을 의미합니다. 클래스 변수이면서 상수이므로, Circle.PI로 접근할 수 있습니다.

요약

  • 인스턴스 변수: 객체마다 고유한 값을 가지며, 객체가 생성될 때 메모리가 할당됩니다.
  • 클래스 변수: static 키워드로 선언되며, 클래스 자체에 속해 모든 객체가 공유합니다.
  • 접근 제어자: public, private, protected 등을 사용하여 클래스 속성에 대한 접근 범위를 제어할 수 있습니다.
  • 상수 필드: final 키워드를 사용해 값을 변경할 수 없는 상수를 선언할 수 있습니다.

자바 클래스 속성은 객체의 상태를 저장하고 관리하는 중요한 요소입니다. 이를 잘 이해하고 적절히 사용하면, 더 효율적이고 유지보수가 용이한 코드를 작성할 수 있습니다.


copyright ⓒ 스타트코딩 all rights reserved.
이메일 : startcodingim@gamil.com