⚡ Java - 객체 지향 프로그래밍 핵심 개념
⚡ Java - 객체 지향 프로그래밍 핵심 개념
🔹 객체 지향 프로그래밍 핵심 개념
▫️ 캡슐화 (Encapsulation
)
1
2
3
4
5
6
7
8
9
10
11
public class Account {
private int balance;
public void deposit(int amount) {
if (amount > 0) balance += amount;
}
public int getBalance() {
return balance;
}
}
- 데이터와 메서드를 하나의 단위(클래스)로 묶는 개념
- 외부에서 직접 접근할 수 없도록 하고,
public
메서드를 통해서만 접근하도록 제한 - 객체의 상태를 숨기고, 의도한 방식으로만 조작되게 함
▫️ 상속 (Inheritance
)
1
2
3
4
5
6
7
8
9
10
11
public class Animal {
public void sound() {
System.out.println("Some sound");
}
}
public class Dog extends Animal {
public void sound() {
System.out.println("Bark");
}
}
- 기존 클래스의 속성과 동작을 물려받아 새로운 클래스를 만드는 개념
- 코드 재사용성을 높이고, 계층적 관계 표현 가능
▫️ 다형성 (Polymorphism
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Animal {
public void sound() {
System.out.println("Some sound");
}
}
public class Cat extends Animal {
public void sound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Cat();
a.sound(); // "Meow" 출력
}
}
- 하나의 인터페이스(또는 부모 클래스)를 통해 다양한 객체의 동작을 다르게 실행할 수 있는 능력
- 오버라이딩(재정의)과 오버로딩(중복정의) 모두 포함
▫️ 추상화 (Abstraction
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
abstract class Shape {
abstract double area();
}
class Circle extends Shape {
private double radius;
public Circle(double r) {
this.radius = r;
}
double area() {
return Math.PI * radius * radius;
}
}
- 불필요한 세부 정보를 숨기고, 필요한 인터페이스만 외부에 제공하는 개념
- 인터페이스나 추상 클래스를 통해 설계 중심의 구조를 만듦
This post is licensed under CC BY 4.0 by the author.