ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • ChatGPT로 Java 공부하기 #1 자바의 기본 문법 및 객체 지향 개념 정리
    ChatGPT로 공부하기/Java 2024. 11. 19. 17:23

     

    1. 자바 기본 문법


    자바의 주요 특징

    • 플랫폼 독립성: JVM(Java Virtual Machine) 덕분에 다양한 운영체제에서 실행 가능
    • 객체 지향 언어: 코드의 재사용성과 유지보수성이 뛰어남
    • 강타입 언어: 데이터 타입을 엄격히 준수

    1.1 기본 문법

    변수와 데이터 타입

    변수는 데이터를 저장하기 위해 메모리에 이름을 붙이는 것입니다.

    자바는 기본적으로 두 가지 타입의 데이터를 사용합니다.

    • 기본형(Primitive types): int, double, boolean, char 등
    • 참조형(Reference types): 클래스, 배열, 인터페이스 등
    public class BasicSyntax {
        public static void main(String[] args) {
            // 기본형 변수 선언 및 초기화
            int age = 30;
            double height = 175.5;
            boolean isAdult = true;
            char grade = 'A';
    
            // 출력
            System.out.println("Age: " + age);
            System.out.println("Height: " + height);
            System.out.println("Is Adult: " + isAdult);
            System.out.println("Grade: " + grade);
        }
    }
    
    

    제어문

    자바는 if, for, while, switch 같은 제어문으로 코드의 흐름을 제어합니다.

    public class ControlStatements {
        public static void main(String[] args) {
            int score = 85;
    
            // if-else 조건문
            if (score >= 90) {
                System.out.println("Grade: A");
            } else if (score >= 80) {
                System.out.println("Grade: B");
            } else {
                System.out.println("Grade: C");
            }
    
            // for 반복문
            for (int i = 0; i < 5; i++) {
                System.out.println("Iteration: " + i);
            }
    
            // while 반복문
            int count = 0;
            while (count < 3) {
                System.out.println("Count: " + count);
                count++;
            }
        }
    }
    
    

    2. 객체 지향 프로그래밍 (OOP)


    OOP의 주요 특징

    1. 캡슐화(Encapsulation): 데이터를 외부로부터 보호하고, 메서드를 통해 접근
    2. 상속(Inheritance): 기존 클래스의 기능을 확장
    3. 다형성(Polymorphism): 하나의 메서드나 객체가 여러 형태를 가질 수 있음
    4. 추상화(Abstraction): 불필요한 세부 사항을 숨기고 중요한 것에 집중

    2.1 클래스와 객체

    클래스는 객체를 생성하기 위한 설계도입니다. 객체는 클래스에서 생성된 실체입니다.

    public class Person {
        // 필드
        String name;
        int age;
    
        // 생성자
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        // 메서드
        public void introduce() {
            System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
        }
    
        // 메인 메서드
        public static void main(String[] args) {
            // 객체 생성
            Person person = new Person("Alice", 25);
            person.introduce();
        }
    }
    
    

    2.2 상속과 다형성

    상속은 코드 재사용성을 높여주고, 다형성은 유연한 코드 작성을 가능하게 합니다.

    // 부모 클래스
    class Animal {
        public void makeSound() {
            System.out.println("Some generic sound");
        }
    }
    
    // 자식 클래스
    class Dog extends Animal {
        @Override
        public void makeSound() {
            System.out.println("Woof woof");
        }
    }
    
    public class PolymorphismExample {
        public static void main(String[] args) {
            Animal myAnimal = new Animal();
            Animal myDog = new Dog();
    
            myAnimal.makeSound(); // Some generic sound
            myDog.makeSound();    // Woof woof
        }
    }
    
    

    3. 실무 적용 예제: 주문 관리 시스템


    간단한 주문 관리를 위한 객체 지향 설계 예제입니다.

    요구사항

    • 고객은 상품을 주문할 수 있다.
    • 주문 정보에는 고객 정보와 상품 정보가 포함된다.
    • 주문 정보를 출력하는 기능이 필요하다.

    코드 구현

    // 상품 클래스
    class Product {
        String name;
        double price;
    
        public Product(String name, double price) {
            this.name = name;
            this.price = price;
        }
    }
    
    // 고객 클래스
    class Customer {
        String name;
        String email;
    
        public Customer(String name, String email) {
            this.name = name;
            this.email = email;
        }
    }
    
    // 주문 클래스
    class Order {
        Customer customer;
        Product product;
    
        public Order(Customer customer, Product product) {
            this.customer = customer;
            this.product = product;
        }
    
        public void printOrderDetails() {
            System.out.println("Customer: " + customer.name + ", Email: " + customer.email);
            System.out.println("Product: " + product.name + ", Price: " + product.price);
        }
    }
    
    // 메인 클래스
    public class OrderManagement {
        public static void main(String[] args) {
            // 객체 생성
            Customer customer = new Customer("Bob", "bob@example.com");
            Product product = new Product("Laptop", 1200.99);
    
            // 주문 생성 및 출력
            Order order = new Order(customer, product);
            order.printOrderDetails();
        }
    }
    
    

     

Designed by Tistory.