자바

자바 클래스와 객체

thebasics 2024. 8. 19. 17:00

목차
1. 클래스와 객체란 무엇인가?
2. 클래스 정의
3. 객체 생성
4. 속성과 메서드
5. 접근 제어자
6. 생성자
7. 예제와 분석
8. 결론 및 추가 학습 자료


1. 클래스와 객체란 무엇인가?

클래스는 객체를 생성하기 위한 청사진(설계도)입니다. 클래스는 속성(필드)과 행동(메서드)을 정의하며, 이를 기반으로 객체를 생성할 수 있습니다. 객체는 클래스로부터 생성된 인스턴스로, 클래스에서 정의한 속성과 메서드를 가집니다. 객체 지향 프로그래밍(OOP)에서 클래스와 객체는 중요한 개념입니다.


2. 클래스 정의

클래스를 정의하려면 'class' 키워드와 클래스 이름을 사용합니다. 클래스는 속성과 메서드를 포함할 수 있습니다.

클래스 정의 구문:

public class 클래스이름 {
    // 속성 (필드)
    자료형 속성이름;

    // 메서드
    반환형 메서드이름(매개변수 목록) {
        // 메서드 본문
    }
}

예제:

public class Person {
    // 속성 (필드)
    String name;
    int age;

    // 메서드
    void introduce() {
        System.out.println("My name is " + name + " and I am " + age + " years old.");
    }
}

3. 객체 생성

객체는 클래스로부터 생성된 인스턴스입니다. 'new' 키워드를 사용하여 객체를 생성합니다.

객체 생성 구문:

클래스이름 객체이름 = new 클래스이름();

예제:

public class Main {
    public static void main(String[] args) {
        // 객체 생성
        Person person = new Person();

        // 속성 값 할당
        person.name = "John";
        person.age = 30;

        // 메서드 호출
        person.introduce();
    }
}

4. 속성과 메서드

클래스는 속성(필드)과 메서드를 가질 수 있습니다. 속성은 객체의 상태를 나타내고, 메서드는 객체의 행동을 정의합니다.

속성과 메서드 예제:

public class Car {
    // 속성 (필드)
    String brand;
    String model;
    int year;

    // 메서드
    void startEngine() {
        System.out.println("Engine started.");
    }

    void displayInfo() {
        System.out.println("Brand: " + brand);
        System.out.println("Model: " + model);
        System.out.println("Year: " + year);
    }
}

객체 생성 및 메서드 호출 예제:

public class Main {
    public static void main(String[] args) {
        // 객체 생성
        Car car = new Car();

        // 속성 값 할당
        car.brand = "Toyota";
        car.model = "Corolla";
        car.year = 2020;

        // 메서드 호출
        car.startEngine();
        car.displayInfo();
    }
}

5. 접근 제어자

접근 제어자는 클래스, 속성, 메서드에 대한 접근 범위를 제어합니다. 자바에서는 'public', 'private', 'protected', 'default' 네 가지 접근 제어자를 제공합니다.

- 'public': 모든 클래스에서 접근할 수 있습니다.
- 'private': 같은 클래스 내에서만 접근할 수 있습니다.
- 'protected': 같은 패키지 내에서 접근할 수 있으며, 상속받은 클래스에서도 접근할 수 있습니다.
- 'default': 같은 패키지 내에서만 접근할 수 있습니다 (명시적으로 접근 제어자를 지정하지 않을 때).

접근 제어자 예제:

public class AccessModifiersExample {
    // public 필드
    public String publicField = "Public Field";

    // private 필드
    private String privateField = "Private Field";

    // protected 필드
    protected String protectedField = "Protected Field";

    // default 필드
    String defaultField = "Default Field";

    // public 메서드
    public void publicMethod() {
        System.out.println("Public Method");
    }

    // private 메서드
    private void privateMethod() {
        System.out.println("Private Method");
    }

    // protected 메서드
    protected void protectedMethod() {
        System.out.println("Protected Method");
    }

    // default 메서드
    void defaultMethod() {
        System.out.println("Default Method");
    }
}

6. 생성자

생성자는 객체가 생성될 때 호출되는 메서드로, 객체의 초기 상태를 설정하는 데 사용됩니다. 생성자는 클래스 이름과 동일하며 반환형이 없습니다.

생성자 구문:

public 클래스이름() {
    // 생성자 본문
}

예제:

public class Person {
    String name;
    int age;

    // 생성자
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    void introduce() {
        System.out.println("My name is " + name + " and I am " + age + " years old.");
    }
}

객체 생성 시 생성자 호출 예제:

public class Main {
    public static void main(String[] args) {
        // 생성자 호출
        Person person = new Person("John", 30);
        person.introduce();
    }
}

7. 예제와 분석

다양한 클래스와 객체 작업을 종합적으로 다루는 예제를 살펴보겠습니다.

종합 예제:

public class Main {
    public static void main(String[] args) {
        // 객체 생성 및 초기화
        Car car1 = new Car("Toyota", "Corolla", 2020);
        Car car2 = new Car("Honda", "Civic", 2019);

        // 메서드 호출
        car1.startEngine();
        car1.displayInfo();

        car2.startEngine();
        car2.displayInfo();
    }
}

class Car {
    // 속성 (필드)
    private String brand;
    private String model;
    private int year;

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

    // 메서드
    public void startEngine() {
        System.out.println("Engine started.");
    }

    public void displayInfo() {
        System.out.println("Brand: " + brand);
        System.out.println("Model: " + model);
        System.out.println("Year: " + year);
    }
}

코드 분석:

- Car 클래스: 자동차를 나타내는 클래스입니다. 'brand', 'model', 'year' 속성을 가지며, 'startEngine'과 'displayInfo' 메서드를 정의합니다.
- 생성자: 'Car' 클래스의 생성자는 객체가 생성될 때 호출되며, 초기 속성을 설정합니다.
- Main 클래스: 'Car' 객체를 생성하고, 생성자와 메서드를 호출하여 정보를 출력합니다.


8. 결론 및 추가 학습 자료

이번 글에서는 자바의 클래스와 객체에 대해 살펴보았습니다. 클래스는 객체를 생성하기 위한 청사진이며, 객체는 클래스에서 정의한 속성과 메서드를 가진 인스턴스입니다. 클래스와 객체를 잘 활용하면 코드의 재사용성을 높이고, 프로그램을 구조화하고 유지보수하기 쉽게 만들 수 있습니다. 클래스와 객체에 대한 이해를 바탕으로 자바 프로그래밍의 기본기를 탄탄히 다질 수 있습니다. 다음은 추가 학습 자료입니다:

추가 학습 자료:
- 자바 공식 문서: [Oracle Java Documentation](https://docs.oracle.com/javase/tutorial/java/javaOO/classes.html)
- 온라인 자바 튜토리얼: [W3Schools Java Classes](https://www.w3schools.com/java/java_classes.asp)
- 자바 코딩 연습 사이트: [GeeksforGeeks](https://www.geeksforgeeks.org/100-days-of-java/)

자바는 강력한 기능을 가진 프로그래밍 언어로, 꾸준히 학습하면 다양한 응용 프로그램을 개발할 수 있습니다. 이번 기회를 통해 자바의 클래스와 객체를 잘 이해하고 더 나아가 복잡한 프로그래밍을 익히길 바랍니다.


이제 자바의 클래스와 객체에 대해 자세히 이해하게 되었습니다. 다음 글에서는 자바의 상속에 대해 다루도록 하겠습니다. 자바의 더 깊은 이해를 위해 계속해서 학습해나가세요!

반응형

'자바' 카테고리의 다른 글

자바 예외 처리  (0) 2024.08.21
자바 인터페이스  (0) 2024.08.20
자바 메서드  (0) 2024.08.18
자바 배열  (0) 2024.08.17
자바 반복문  (0) 2024.08.16