캡슐화(Encapsulation)
class Person {
private String name; // 캡슐화된 데이터
public String getName() { // 데이터 접근을 위한 메서드
return name;
}
public void setName(String name) {
this.name = name;
}
}
상속(Inheritance)
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
다형성(Polymorphism)
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
추상화(Abstraction)
abstract class Shape {
abstract void draw(); // 추상 메서드
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle");
}
}
객체지향 프로그래밍(OOP)의 4대 특성에 대해 실습 가능한 아이디어를 Java와 Spring을 중심으로 설명드리겠습니다. 신입 취준생 입장에서 실습을 통해 이해를 심화하고, 포트폴리오로 활용할 수도 있는 방향으로 제안드릴게요.
실습 아이디어: 회원 관리 시스템
목표: 데이터를 캡슐화하고, 접근 메서드를 통해 데이터 보호와 무결성 유지.
예제:
실습 코드:
public class Member {
private String name;
private String password;
// Getter and Setter with validation
public String getName() {
return name;
}
public void setName(String name) {
if (name == null || name.isEmpty()) {
throw new IllegalArgumentException("Name cannot be null or empty");
}
this.name = name;
}
public String getPassword() {
return "****"; // 비밀번호 노출 금지
}
public void setPassword(String password) {
if (password.length() < 6) {
throw new IllegalArgumentException("Password must be at least 6 characters long");
}
this.password = password;
}
}
Spring 실습:
@RequestBody로 JSON 입력을 받아 Member 객체로 변환.@Valid와 @NotNull로 처리.@RestController
public class MemberController {
@PostMapping("/register")
public String register(@Valid @RequestBody MemberDto memberDto) {
// Business Logic
return "회원 등록 완료!";
}
}
실습 아이디어: 도형 클래스 계층 구조
목표: 공통 속성과 메서드를 부모 클래스에 정의하고, 자식 클래스에서 확장.
예제:
Shape를 정의하고, Circle과 Rectangle에서 상속.실습 코드:
public class Shape {
public void draw() {
System.out.println("Drawing a shape");
}
}
public class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
public class Rectangle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a rectangle");
}
}
public class Main {
public static void main(String[] args) {
Shape shape = new Circle();
shape.draw(); // "Drawing a circle"
}
}
Spring 실습:
BaseService를 정의하고, 이를 상속한 UserService, AdminService 등을 구현.BaseService에, 추가 기능은 자식 클래스에 작성.실습 아이디어: 다양한 결제 수단 처리
목표: 인터페이스나 부모 클래스를 활용해 다양한 구현체를 다룰 수 있도록 다형성을 적용.
예제:
Payment 인터페이스를 정의하고, CreditCardPayment, PaypalPayment 구현체 작성.Payment 타입으로 처리.실습 코드:
public interface Payment {
void pay(double amount);
}
public class CreditCardPayment implements Payment {
@Override
public void pay(double amount) {
System.out.println("Paid " + amount + " using Credit Card.");
}
}
public class PaypalPayment implements Payment {
@Override
public void pay(double amount) {
System.out.println("Paid " + amount + " using PayPal.");
}
}
public class Main {
public static void main(String[] args) {
Payment payment = new CreditCardPayment();
payment.pay(100.0); // "Paid 100.0 using Credit Card."
}
}
Spring 실습:
Payment 구현체를 @Service로 등록하고, @Qualifier를 통해 원하는 구현체를 선택.@RestController
public class PaymentController {
private final Payment payment;
public PaymentController(@Qualifier("creditCardPayment") Payment payment) {
this.payment = payment;
}
@PostMapping("/pay")
public String pay(@RequestParam double amount) {
payment.pay(amount);
return "결제 완료!";
}
}
실습 아이디어: 게시판 관리 시스템
목표: 추상 클래스를 활용해 공통 기능을 정의하고, 구체적인 기능은 자식 클래스에서 구현.
예제:
Board 추상 클래스를 작성하고, NoticeBoard, QnaBoard에서 상속.실습 코드:
public abstract class Board {
public abstract void createPost(String content);
public void commonFeature() {
System.out.println("This is a common feature for all boards.");
}
}
public class NoticeBoard extends Board {
@Override
public void createPost(String content) {
System.out.println("Creating a notice post: " + content);
}
}
public class QnaBoard extends Board {
@Override
public void createPost(String content) {
System.out.println("Creating a Q&A post: " + content);
}
}
Spring 실습:
NotificationService를 추상 클래스로 정의하고, SMS와 이메일 구현체를 작성.