전공/객체지향프로그래밍

OOP) 클래스와 객체

공부하려구요 2024. 1. 2. 17:28
728x90
반응형

클래스

  • 객체를 생성하기 위한 '틀'
  • 객체의 상태를 나타내는 필드(색깔, 모델명)와 객체의 행동(움직임, 멈춤)을 나타내는 메서드를 포함

객체

  • 각자 독립된 메모리 공간을 가짐
  • 자동차 클래스를 통해 현대자동차, 기아자당차 두 객체를 생성한 후 서로 다르게 설정, 동작 가능
public class Car {
    // 필드 선언
    private String color;
    private String model;

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

    // 메서드 정의
    public void run() {
        System.out.println(model + "가 달립니다.");
    }

    public void stop() {
        System.out.println(model + "가 멈춥니다.");
    }
}

 

public class Main {
    public static void main(String[] args) {
        // 객체 생성
        Car hyundaiCar = new Car("Blue", "Sonata");
        Car kiaCar = new Car("Red", "K5");

        // 메서드 사용
        hyundaiCar.run();  // "Sonata가 달립니다." 출력
        kiaCar.stop();     // "K5가 멈춥니다." 출력
    }
}
728x90
반응형