목차
1. static 키워드와 클래스 변수
2. 인터페이스(Interface)
3. 추상 클래스(abstract class)
static 키워드와 클래스 변수| 항목 | static 필드/메서드 | 일반 필드/메서드 |
|---|---|---|
| 선언 위치 | 클래스 내부 | 클래스 내부 |
| 메모리 위치 | Method Area(Class Area) | Heap |
| 객체 필요 여부 | x 객체 없이 사용 가능 | o |
public class StaticExample {
public static int counter = 0; // static 변수
public int serialNumber; // 인스턴스 변수
public StaticExample() {
counter++;
serialNumber = counter;
}
public static void printCounter() {
System.out.println("현재 카운터: " + counter);
}
}
StaticExample.printCounter(); // 객체 생성 없이 호출 가능
StaticExample a = new StaticExample();
System.out.println(a.serialNumber); // 1
StaticExample b = new StaticExample();
System.out.println(b.serialNumber); // 2
📌 static은 모든 인스턴스가 공유. 객체마다 다른 값을 가지려면 static을 사용하지 않아야 합니다.
interface)interface Flyable {
void fly();
void land();
}
class Bird implements Flyable {
public void fly() {
System.out.println("Bird flying");
}
public void land() {
System.out.println("Bird landing");
}
}
abstract class)abstract class Animal {
String name;
public abstract void makeSound(); // 추상 메서드
public void breathe() { // 일반 메서드
System.out.println("숨을 쉽니다.");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("멍멍!");
}
}
| 구분 | interface | abstract class | 일반 class |
|---|---|---|---|
| 객체 생성 | x | x | o |
| 메서드 | 모두 추상 | 추상 + 일반 가능 | 일반 메서드 |
| 필드 | public static final만 허용 | 일반 필드 가능 | 일반 필드 가능 |
| 다중 상속 | o | ||
| 용도 | 기능 규약 | 기본 구현 제공 + 확장 | 실체 구현 |
interface: 서로 다른 클래스에 같은 기능을 강제하고 싶을 때abstract class: 기본 로직이 있고 일부만 자식이 구현하게 할 때class: 완전한 기능을 가진 실체 객체를 만들 때interface Workable {
void doWork();
}
abstract class Employee {
String name;
int salary;
public abstract void calculatePay();
public void showInfo() {
System.out.println("직원 이름: " + name);
}
}
class Engineer extends Employee implements Workable {
public void calculatePay() {
salary += 1000;
}
public void doWork() {
System.out.println("코딩합니다.");
}
}
인터페이스는 "해야 할 일", 추상 클래스는 "공통 구조", 일반 클래스는 "구현체".
static: 모든 인스턴스에서 공유하는 클래스 변수/메서드interface: 기능을 정의만 하고, 반드시 구현하도록 규약abstract class: 기능을 일부 구현하고, 확장을 위한 중간 단계