객체지향 프로그래밍 개념 정리

YYY·2025년 2월 3일

1. 클래스(Class)란?

객체를 만들기 위한 설계도(틀, Blueprint)
예를 들어, 자동차 설계도가 있으면 그 설계도를 바탕으로 여러 대의 자동차를 만들 수 있다.

📌 클래스 예제

class Car {
    // 속성 (변수)
    String brand;
    int speed;

    // 동작 (메서드)
    void drive() {
        System.out.println(brand + " is driving at " + speed + " km/h.");
    }
}

2. 객체(Object)란?

클래스를 기반으로 만들어진 실체(Instance, 인스턴스)

📌 객체 생성과 사용 예제

public class Main {
    public static void main(String[] args) {
        // 객체 생성 (인스턴스화)
        Car myCar = new Car();

        // 객체의 속성 설정
        myCar.brand = "Tesla";
        myCar.speed = 100;

        // 객체의 메서드 호출
        myCar.drive(); // 출력: Tesla is driving at 100 km/h.
    }
}

3. 클래스와 객체의 관계

car = class, mycar = 객체

4. 생성자

객체가 생성될 때 자동으로 호출되는 메서드

class Car {
    String brand;
    int speed;

    // 생성자
    Car(String brand, int speed) {
        this.brand = brand;
        this.speed = speed;
    }

    void drive() {
        System.out.println(brand + " is driving at " + speed + " km/h.");
    }
}

public class Main {
    public static void main(String[] args) {
        // 생성자를 사용하여 객체 생성
        Car myCar = new Car("BMW", 120);
        myCar.drive(); // 출력: BMW is driving at 120 km/h.
    }
}

5. 예시

package org.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;

public class Main {
    public static void main(String[] args) {
        try{
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); #객체만 호출함
            String oneLine = br.readLine(); #여기서 입력 받는거임(메소드 실행)
            System.out.println(oneLine);
            br.close();
        } catch (IOException e){
            System.out.println("입력오류발생");
            e.printStackTrace(); #예외객체
        } #IOException는 클래스



    }
}

다른 클래스의 메소드를 사용하기 위해 클래스를 객체로 생성한다고 보면 됨.

profile
무지렁이 탈출기

0개의 댓글