클래스 (Class)
클래스는 객체를 생성하기 위한 설계도로, 속성과 동작을 함께 정의합니다. 예를 들어 자동차의 색상과 문의 개수를 필드로 갖고, 주행 기능을 메서드로 구현할 수 있습니다.
public class Automobile {
String paintColor;
int doorCount;
public Automobile(String paintColor, int doorCount) {
this.paintColor = paintColor;
this.doorCount = doorCount;
}
void move() {
System.out.println("자동차가 이동 중입니다.");
}
}
객체 (Object)
객체는 클래스의 인스턴스로, 실제 메모리에 할당되어 동작하는 단위입니다. new 키워드를 사용해 생성하며, 정의된 메서드를 호출할 수 있습니다.
Automobile myVehicle = new Automobile("파란색", 4);
myVehicle.move(); // "자동차가 이동 중입니다." 출력
상속 (Inheritance)
하위 클래스가 상위 클래스의 특성을 물려받아 재사용하고 확장할 수 있는 기능입니다. extends 키워드를 사용하며, 중복 코드를 줄이고 계층 구조를 명확히 합니다.
public class ElectricAutomobile extends Automobile {
int batteryCapacity;
public ElectricAutomobile(String paintColor, int doorCount, int batteryCapacity) {
super(paintColor, doorCount);
this.batteryCapacity = batteryCapacity;
}
void recharge() {
System.out.println("배터리를 충전합니다.");
}
}
다형성 (Polymorphism)
같은 타입의 참조 변수로 서로 다른 객체를 다룰 수 있는 능력을 의미합니다. 메서드 오버라이딩을 통해 실행 시점에 적절한 메서드가 호출됩니다.
public class Transport {
void start() {
System.out.println("운송 수단이 시작됩니다.");
}
}
public class Truck extends Transport {
@Override
void start() {
System.out.println("트럭이 시동을 겁니다.");
}
}
캡슐화 (Encapsulation)
데이터와 그 데이터를 조작하는 함수를 하나로 묶고, 외부로부터 내부 상태를 보호합니다. private 필드와 public 접근자 메서드(getter/setter)를 통해 제어합니다.
public class Human {
private String fullName;
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
}
추상화 (Abstraction)
복잡한 내부 로직을 숨기고, 필요한 인터페이스만 노출하여 사용을 단순화합니다. 추상 클래스나 인터페이스를 통해 구현됩니다.
public abstract class Creature {
public abstract void vocalize();
}
public interface Swimmable {
void swim();
}
public class Duck extends Creature implements Swimmable {
@Override
public void vocalize() {
System.out.println("꽥꽥");
}
@Override
public void swim() {
System.out.println("물에서 노니는 중");
}
}