언어/Java

4. Java 객체지향 프로그래밍 (클래스, 상속, 다형성, 인터페이스)

뉴비2 2024. 11. 10. 19:02

왜 객체지향 프로그래밍을 배워야 할까?

  1. 모듈성: 복잡한 시스템을 작은 부분으로 나누어 관리
  2. 재사용성: 코드 중복을 줄이고 효율적인 개발 가능
  3. 유지보수성: 변경에 유연하고 확장 가능한 소프트웨어 설계
  4. 추상화: 복잡한 시스템을 간단한 모델로 표현

클래스와 객체: 현실을 코드로 모델링하기

public class Car {
    // 캡슐화된 private 멤버 변수
    private String model;
    private String color;
    private int speed;

    // 생성자 오버로딩
    public Car() {
        this("미정", "white");
    }

    public Car(String model, String color) {
        this.model = model;
        this.color = color;
        this.speed = 0;
    }

    // 메서드
    public void accelerate() {
        if (speed < 200) {
            speed += 10;
            System.out.println("현재 속도: " + speed + "km/h");
        }
    }

    // 게터와 세터
    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }
}

public class CarDemo {
    public static void main(String[] args) {
        Car myCar = new Car("소나타", "black");
        myCar.accelerate();
    }
}

클래스 설계의 핵심 원칙

  1. 단일 책임 원칙: 클래스는 하나의 명확한 책임만 가져야 합니다.
  2. 캡슐화: 데이터 은닉과 보호를 위해 private 멤버 사용
  3. 생성자 오버로딩: 다양한 방식의 객체 생성 지원

상속: 코드 재사용과 계층적 설계

// 부모 클래스
public abstract class Vehicle {
    protected String name;
    protected int maxSpeed;

    public Vehicle(String name, int maxSpeed) {
        this.name = name;
        this.maxSpeed = maxSpeed;
    }

    public abstract void move();
}

// 자식 클래스들
public class Car extends Vehicle {
    private int wheels;

    public Car(String name, int maxSpeed, int wheels) {
        super(name, maxSpeed);
        this.wheels = wheels;
    }

    @Override
    public void move() {
        System.out.println(name + "가 도로를 달립니다.");
    }
}

public class Airplane extends Vehicle {
    private int wings;

    public Airplane(String name, int maxSpeed, int wings) {
        super(name, maxSpeed);
        this.wings = wings;
    }

    @Override
    public void move() {
        System.out.println(name + "가 하늘을 날아갑니다.");
    }
}

다형성: 유연한 설계의 핵심

public class PolymorphismDemo {
    public static void main(String[] args) {
        // 다형성을 활용한 객체 배열
        Vehicle[] vehicles = {
            new Car("소나타", 200, 4),
            new Airplane("보잉", 900, 2)
        };

        // 공통 메서드 호출 - 각 객체의 고유한 move() 실행
        for (Vehicle vehicle : vehicles) {
            vehicle.move();
        }
    }
}

추상 클래스와 인터페이스: 설계의 청사진

// 인터페이스
public interface Chargeable {
    void charge();
    default void displayChargeStatus() {
        System.out.println("충전 중...");
    }
}

// 추상 클래스
public abstract class ElectronicDevice implements Chargeable {
    protected String deviceName;

    public ElectronicDevice(String deviceName) {
        this.deviceName = deviceName;
    }

    // 추상 메서드
    public abstract void turnOn();
    public abstract void turnOff();
}

// 구현 클래스
public class Smartphone extends ElectronicDevice {
    public Smartphone(String deviceName) {
        super(deviceName);
    }

    @Override
    public void turnOn() {
        System.out.println(deviceName + " 전원 켜짐");
    }

    @Override
    public void turnOff() {
        System.out.println(deviceName + " 전원 꺼짐");
    }

    @Override
    public void charge() {
        System.out.println(deviceName + " 충전 시작");
    }
}