추상 메소드

KKH_94·2023년 6월 7일
0

JAVA

목록 보기
14/36
abstract class Shape {
    abstract double area(); // Abstract method

    void display() {
        System.out.println("This is a shape.");
    }
}

class Rectangle extends Shape {
    private double width;
    private double height;

    Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    double area() {
        return width * height;
    }
}

class Circle extends Shape {
    private double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    double area() {
        return Math.PI * radius * radius;
    }
}

public class Main {
    public static void main(String[] args) {
        Rectangle rectangle = new Rectangle(5, 10);
        Circle circle = new Circle(7);

        rectangle.display();
        System.out.println("Area of rectangle: " + rectangle.area());

        circle.display();
        System.out.println("Area of circle: " + circle.area());
    }
}

위의 예시에서 추상 메서드 area()와 비추상 메서드 display()를 포함하는 추상 클래스 Shape가 있습니다. Shape 클래스는 abstract 키워드를 사용하여 abstract로 표시됩니다.

area() 메서드는 메서드 본문을 생략하고 메서드 선언을 세미콜론으로 종료하여 추상 메서드로 선언합니다. 이는 Shape에서 상속되는 모든 클래스가 area() 메소드의 자체 구현을 제공해야 함을 의미합니다.

Rectangle 및 Circle 클래스는 Shape의 하위 클래스이며 area() 메서드의 자체 구현을 제공합니다. 추상적인 area() 메서드를 재정의하고 면적에 대한 고유한 계산을 제공합니다.

Main 클래스에서 Rectangle 및 Circle 클래스의 개체를 만들고 여기에 display() 및 area() 메서드를 호출합니다.

추상 클래스의 인스턴스를 직접 만들 수는 없습니다. 추상 클래스에 정의된 모든 추상 메서드에 대한 구현을 제공하는 구체적인 하위 클래스의 인스턴스만 만들 수 있습니다.

프로그램을 실행하면 다음과 같은 출력이 표시됩니다.

csharp
Copy code
This is a shape.
Area of rectangle: 50.0
This is a shape.
Area of circle: 153.93804002589985

보시다시피 각 서브 클래스의 area() 메서드는 특정 객체 유형을 기반으로 호출되며 적절한 면적 계산이 수행됩니다.

profile
_serendipity

0개의 댓글