static 키워드, 클래스 변수, 인터페이스, 추상 클래스

labbiel·2025년 4월 24일

자바

목록 보기
6/9
post-thumbnail

목차
1. static 키워드와 클래스 변수
2. 인터페이스(Interface)
3. 추상 클래스(abstract class)



static 키워드와 클래스 변수

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");
    }
}

사용 목적

  • 다형성 구현: 부모 타입(interface)으로 다양한 자식 객체를 참조할 수 있습니다.
  • 기능 표준화: 서로 다른 클래스에서 같은 기능을 강제 구현하게 합니다.
  • 유지보수성 향상: 기능 확장 및 수정 시 유연하게 대응 가능합니다.

추상 클래스 (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 vs abstract class vs class 비교표

구분interfaceabstract class일반 class
객체 생성xxo
메서드모두 추상추상 + 일반 가능일반 메서드
필드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: 기능을 일부 구현하고, 확장을 위한 중간 단계
  • 클래스를 설계할 때는 공통 요소 → 상위로 추상화, 구체적 기능 → 하위로 구현이 원칙

0개의 댓글