4 minute read

클래스(Class)

특징

  • 클래스가 정의하는 것들
    • 어트리뷰트(데이터/상태): 각각의 객체에 속하게 될 변수들.
    • 메서드(행동): 객체가 실행할 수 있는 함수.
  • 클래스는 객체가 아니다. 객체를 위한 청사진이다.
  • 인스턴스가 실행되기 전까지 메모리를 사용하지 않는다.

코드 예시

  • 자동차에 대한 정의 사항이다.
  • 필드와 메서드를 정의한다.
  • 객체를 생성하기 위한 생성자가 있다.
public class Car {
    // Attributes (fields) - the STATE of the object
    private String brand;
    private String model;
    private String color;
    private boolean isRunning;
    
    // Constructor - special method to initialize new objects
    public Car(String brand, String model, String color) {
        this.brand = brand;
        this.model = model;
        this.color = color;
        this.isRunning = false; // default value
    }
    
    // Methods - the BEHAVIOR of the object
    public void startEngine() {
        this.isRunning = true;
        System.out.println("The " + color + " " + brand + " " + model + "'s engine is now running.");
    }
    
    public void stopEngine() {
        this.isRunning = false;
        System.out.println("The engine has been stopped.");
    }
    
    public void honk() {
        System.out.println("Beep Beep!");
    }
    
    // Getter methods to access private fields
    public String getBrand() { return brand; }
    public String getModel() { return model; }
    public String getColor() { return color; }
    public boolean isRunning() { return isRunning; }
}

➕ 정적 멤버가 있는 클래스와 객체의 차이점은?

  • 클래스는 실제 값이 있다기보다는 생성될 객체들에 포함될 요소들을 정의하는 역할을 한다.
    • 그렇다면 실제 값, 즉 정적 값이 있는 클래스는 어떨까?
    • 클래스에 실제 값이 있으니까 객체라고 할 수 있을까?
  • 클래스에 있는 값은 상태가 없다.
    • 클래스의 정적 값들은 유틸리티, 상수, 공유할 데이터로 쓰인다.
    • 정적 값이 있더라도 인스턴스처럼 쓰이지 않는다. 값이 변하지 않아서 실생활을 나타낼 수 없다.
    • 예시: 자동차의 경우 제조사, 생성된 자동차의 총 수량 등을 설정할 수 있다.
      public class Car {
          // Static fields (class-level) - shared by all instances
          public static int totalCarsCreated = 0;
          public static final String MANUFACTURER = "AutoCorp";
            
          // Static method
          public static void displayManufacturerInfo() {
              System.out.println("Manufacturer: " + MANUFACTURER);
              System.out.println("Total cars created: " + totalCarsCreated);
          }
      }
    
    • 용례
      public class Main {
          public static void main(String[] args) {
              // Access static field without creating an instance
              System.out.println("Manufacturer: " + Car.MANUFACTURER);
                
              // Access static field to see it's shared across all instances
              System.out.println("Total cars: " + Car.totalCarsCreated);
                
              // Call static method
              Car.displayManufacturerInfo();
          }
      }
    
  • 인스턴스와 객체의 값은 상태가 있다.
    • 저마다의 신원과 상태가 있는 엔티티를 모델링할 목적으로 쓰인다.
    • 예시: 자동차의 경우 모델, 색, 출시 년도 등을 포함할 수 있다.
      public class Car {
          // Instance fields (object-level) - unique to each instance
          public String model;
          public String color;
          public int year;
            
          // Constructor
          public Car(String model, String color, int year) {
              this.model = model;
              this.color = color;
              this.year = year;
              totalCarsCreated++; // Increment static counter for each new car
          }
            
          // Instance method
          public void displayCarInfo() {
              System.out.println("Model: " + model + ", Color: " + color + ", Year: " + year);
          }
      }
    
    • 용례
      public class Main {
          public static void main(String[] args) {
                
              // Create instances (objects)
              Car car1 = new Car("Sedan", "Red", 2023);
              Car car2 = new Car("SUV", "Blue", 2024);
                
              // Use instance methods
              car1.displayCarInfo();
              car2.displayCarInfo();
          }
      }
    

객체(Object)

특징

  • “객체와 객체를 만든 클래스와의 관련성”이라는 맥락을 제외하고는 인스턴스와 차이가 없다.
  • 객체는 메모리를 차지한다. 즉 메모리에 할당된다.

➕ 인스턴스와의 맥락적 차이 예시

  • ✅ myCar는 Car의 인스턴스이다. → 클래스와 객체의 관련성을 보여주어 자연스러움
  • ✅ myCar은 객체이다. → 대상이 무엇인지 나타내어 자연스러움
  • ❌ myCar는 Car의 객체이다. → 아주 틀린 말은 아니지만 부자연스러움
    • 객체 → 정체성을 나타내는 용어. “그 사람은 목수이다”, “저건 탁자이다”
    • 인스턴스: 관계성을 나타내는 용어. “그 사람은 윤희의 딸이다”, “저 강아지는 철수의 반려동물이다”
    • 정체성을 나타내는 용어를 관계성을 설명하는 맥락에서 사용했으니 어색한 것!

코드 예시

  • 예시
    • 모든 객체는 클래스가 정의한 필드들에 대한 자신만의 데이터를 지닌다.
      public class Main {
          public static void main(String[] args) {
              // Creating INSTANCES (OBJECTS) of the Car class
              // Each 'new' keyword creates a new instance
                
              Car myCar = new Car("Tesla", "Model 3", "red");
              Car yourCar = new Car("Toyota", "Camry", "blue");
              Car companyCar = new Car("Ford", "Explorer", "white");
                
              // These are all INSTANCES of the Car class
              // They are also OBJECTS
                
              // Each instance has its own separate data
              System.out.println("My car: " + myCar.getColor() + " " + myCar.getBrand());
              System.out.println("Your car: " + yourCar.getColor() + " " + yourCar.getBrand());
                
              // They can perform actions independently
              myCar.startEngine();  // Only myCar's engine starts
              yourCar.honk();       // Only yourCar honks
                
              System.out.println("Is my car running? " + myCar.isRunning());     // true
              System.out.println("Is your car running? " + yourCar.isRunning()); // false
          }
      }
    

인스턴스(Instance)

특징

  • “객체와 객체를 만든 클래스와의 관련성”이라는 맥락을 제외하고는 인스턴스와 차이가 없다.
  • 모든 인스턴스는 객체이다.
  • 인스턴스는 메모리를 차지한다. 즉 메모리에 할당된다.

➕ 서비스를 하는 실무에서는 인스턴스와 객체를 엄밀하게 구분하지 않는다

  • 개발자가 “어떤 클래스에서 인스턴스를 만들었어”라고 하든 “어떤 클래스에서 객체를 만들었어”라고 하든 말의 의도가 같다.
  • 대부분의 프로그래밍 언어에서 문서나 구문에서 둘의 차이를 강제하지 않는다.
  • 학술적 분야, 기술 인터뷰 등의 경우는 둘을 구분하기도 한다.

코드 예시

  • 예시
    • 모든 인스턴스는 클래스가 정의한 필드들에 대한 자신만의 데이터를 지닌다.
      public class Main {
          public static void main(String[] args) {
              // Creating INSTANCES (OBJECTS) of the Car class
              // Each 'new' keyword creates a new instance
                
              Car myCar = new Car("Tesla", "Model 3", "red");
              Car yourCar = new Car("Toyota", "Camry", "blue");
              Car companyCar = new Car("Ford", "Explorer", "white");
                
              // These are all INSTANCES of the Car class
              // They are also OBJECTS
                
              // Each instance has its own separate data
              System.out.println("My car: " + myCar.getColor() + " " + myCar.getBrand());
              System.out.println("Your car: " + yourCar.getColor() + " " + yourCar.getBrand());
                
              // They can perform actions independently
              myCar.startEngine();  // Only myCar's engine starts
              yourCar.honk();       // Only yourCar honks
                
              System.out.println("Is my car running? " + myCar.isRunning());     // true
              System.out.println("Is your car running? " + yourCar.isRunning()); // false
          }
      }
    

Categories:

Updated: