Sparta/자료 & 기타

JAVA 객체 활용

hyunjg94 2025. 3. 3. 21:25

1. 클래스 ( Class )

● 클래스란? 현실 세계의 개념을 코드로 표현한 설계도

● 속성 ( Attribute ) & 메서드 ( Method )

class Student {
    int id;
    String name;
    int age;
    String major;
    
    // 생성자
    Student(int id, String name, int age, String major) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.major = major;
    }
}

// 객체 생성
Student student1 = new Student(20250101, "박성원", 30, "CS");

 

● 메모리 구조

  ○ 기본 데이터 타입 → Stack 영역에 저장

  ○ 참조 데이터 타입 → Heap 영역에 저장

  ○ null → 객체를 참조하지 않는 상태


2. 캡슐화 ( Encapsulation )

● 내부 구현을 외부에서 직접 접근하지 못하도록 보호

● 접근 제어자 ( Access Modifiers )

접근제어자 같은 클래스 같은 패키지 상속받은 클래스 다른 패키지
public O O O O
protected O O O X
default O O X X
private O X X X

 

● 사용 예시

public class Person {
    private String name;
    private int age;

    // Getter
    public String getName() {
        return name;
    }

    // Setter
    public void setAge(int age) {
        if (age > 0) {
            this.age = age;
        } else {
            System.out.println("나이는 0보다 커야 합니다.");
        }
    }
}

3. Getter & Setter 활용

● 데이터 보호 및 캡슐화 강화

● 기본적인 Getter & Setter

public int getAge() {
    return age;
}

public void setAge(int age) {
    if (age > 0) {
        this.age = age;
    } else {
        System.out.println("나이는 0보다 커야 합니다.");
    }
}

 

● 가공된 데이터 반환

public String getFormattedName() {
    return "이름: " + this.name;
}

public void updateName(String name) {
    this.name = name + "님";
}

'Sparta > 자료 & 기타' 카테고리의 다른 글

Java 객체지향 프로그래밍(OOP) 정리  (1) 2025.03.07
JAVA 프로그래밍 기초  (0) 2025.03.03
Spata 참여!  (0) 2025.03.03