본문 바로가기
JAVA

[JAVA] Abstract

by kwh_coding 2024. 3. 26.

abstract는 자바에서 클래스나 메서드를 추상화할 때 사용되는 키워드이다. 추상 클래스는 객체를 직접적으로 생성할 수 없고, 추상 메서드는 메서드의 구현이 없는 상태로 선언된다.

1. 추상 클래스 (Abstract Class):

추상 클래스는 하나 이상의 추상 메서드를 포함하며, 객체를 직접적으로 생성할 수 없다. 추상 클래스는 상속을 통해 자식 클래스에게 메서드의 구현을 강제할 수 있다.

abstract class Shape {
    abstract void draw(); // 추상 메서드
    
    void display() {
        System.out.println("Shape");
    }
}

class Circle extends Shape {
    void draw() {
        System.out.println("circle.");
    }
}

class Rectangle extends Shape {
    void draw() {
        System.out.println("rectangle.");
    }
}

public class Example {
    public static void main(String[] args) {
        Shape circle = new Circle();
        Shape rectangle = new Rectangle();
        
        circle.draw(); // 출력: circle.
        circle.display(); // 출력: Shape.
        
        rectangle.draw(); // 출력: rectangle.
        rectangle.display(); // 출력: Shape.
    }
}

 

2. 추상 메서드 (Abstract Method):

추상 메서드는 선언만 되고 구현이 없는 메서드를 의미한다. 추상 메서드는 세미콜론(;)으로 끝나며, 하위 클래스에서 반드시 구현돼야 한다.

abstract class Animal {
    abstract void sound(); // 추상 메서드
}

class Dog extends Animal {
    void sound() {
        System.out.println("멍멍");
    }
}

class Cat extends Animal {
    void sound() {
        System.out.println("야옹");
    }
}

public class Example {
    public static void main(String[] args) {
        Animal dog = new Dog();
        Animal cat = new Cat();
        
        dog.sound(); // 출력: 멍멍
        cat.sound(); // 출력: 야옹
    }
}

 


  • 추상 클래스는 하나 이상의 추상 메서드를 포함하며, 일반 메서드도 가질 수 있다.
  • 추상 클래스는 abstract 키워드를 사용하여 선언된다.
  • 추상 메서드는 메서드 시그니처만을 가지고 있으며, 중괄호 {} 내에 구현이 없다.
  • 추상 클래스의 인스턴스를 직접 생성할 수 없지만, 추상 클래스의 참조 변수를 사용하여 하위 클래스의 인스턴스를 참조할 수 있다.
  • 추상 클래스는 new로 객체 생성이 불가능하다.

'JAVA' 카테고리의 다른 글

[JAVA] Interface  (0) 2024.03.27
[JAVA] Abstract 예제  (0) 2024.03.26
[JAVA] static  (0) 2024.03.25
[JAVA] Call By Value / Call By Reference  (0) 2024.03.25
[JAVA] 오버로딩(Overloading)과 오버라이드(Override)  (0) 2024.03.25