자바 객체 지향 프로그래밍의 기초와 클래스 구조 설계

자바(Java)는 객체 지향 프로그래밍(OOP) 언어로, 모든 데이터와 로직을 객체 단위로 관리합니다. 객체 지향의 핵심은 데이터를 보호하는 캡슐화와 이를 다루는 인터페이스(메서드)를 정의하는 것입니다.

1. 클래스 정의와 캡슐화

객체의 상태를 나타내는 변수는 보통 private 접근 제어자를 사용하여 외부의 직접적인 접근을 차단합니다. 대신 public 메서드인 Getter와 Setter를 통해 안전하게 데이터를 읽고 수정합니다. CircleGeometry.java

public class CircleGeometry {
    // 상수 정의 (static final)
    public static final double DEFAULT_RADIUS = 1.0;
    public static final String DEFAULT_COLOR = "blue";

    private double radius;
    private String color;

    // 기본 생성자
    public CircleGeometry() {
        this.radius = DEFAULT_RADIUS;
        this.color = DEFAULT_COLOR;
    }

    // 매개변수가 있는 생성자 (오버로딩)
    public CircleGeometry(double radius) {
        this.radius = radius;
        this.color = DEFAULT_COLOR;
    }

    public CircleGeometry(double radius, String color) {
        this.radius = radius;
        this.color = color;
    }

    // Getter 및 Setter 메서드
    public double getRadius() {
        return radius;
    }

    public void setRadius(double radius) {
        this.radius = radius;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    // 인스턴스 정보 요약
    @Override
    public String toString() {
        return String.format("CircleGeometry[radius=%.2f, color=%s]", radius, color);
    }

    // 넓이 계산 메서드
    public double calculateArea() {
        return Math.pow(this.radius, 2) * Math.PI;
    }
}
TestGeometry.java

public class TestGeometry {
    public static void main(String[] args) {
        CircleGeometry circle1 = new CircleGeometry(2.5, "green");
        System.out.println(circle1.toString());
        System.out.println("넓이: " + circle1.calculateArea());

        CircleGeometry circle2 = new CircleGeometry();
        System.out.println("기본 원 색상: " + circle2.getColor());
    }
}

2. 좌표 기반의 클래스 설계 및 메서드 오버로딩

객체 간의 상호작용을 설계할 때 메서드 오버로딩을 사용하면 동일한 이름의 메서드로 다양한 입력 파라미터를 처리할 수 있습니다. Point2D.java

public class Point2D {
    private int x;
    private int y;

    public Point2D() {
        this.x = 0;
        this.y = 0;
    }

    public Point2D(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() { return x; }
    public void setX(int x) { this.x = x; }

    public int getY() { return y; }
    public void setY(int y) { this.y = y; }

    public void setLocation(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public String toString() {
        return "(" + x + ", " + y + ")";
    }

    // 좌표값(x, y)을 직접 받아 거리 계산
    public double getDistance(int x, int y) {
        int xDiff = this.x - x;
        int yDiff = this.y - y;
        return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
    }

    // 다른 Point2D 객체를 받아 거리 계산 (메서드 오버로딩)
    public double getDistance(Point2D other) {
        return getDistance(other.x, other.y);
    }
}

3. 멤버 변수 접근과 명명 규칙

자바에서는 멤버 변수와 지역 변수의 이름이 같을 때 this 키워드를 사용하여 현재 인스턴스의 멤버임을 명시합니다. 또한, 필드의 타입에 따라 접근자(Getter)의 명명 규칙이 달라집니다.
  • 일반 객체 및 기본 타입: getXxx() / setXxx()
  • boolean 타입: isXxx() / setXxx()

public class UserProfile {
    private String username;
    private boolean active;

    // String 타입의 Getter/Setter
    public String getUsername() {
        return this.username;
    }
    public void setUsername(String username) {
        this.username = username;
    }

    // boolean 타입의 Getter/Setter
    public boolean isActive() {
        return this.active;
    }
    public void setActive(boolean active) {
        this.active = active;
    }
}

태그: java OOP ClassDesign Encapsulation Methods

10월 8일 20:29에 게시됨