Skip to content

PHP

abstract class : 부모 class로 사용되며 자식(extends 한)에게 abstract method를 강제함(그들만의 방식으로)

Author
siwon
Date
2023-09-19 16:34
Views
1136


추상 클래스(abstract class)는 객체 지향 프로그래밍에서 다음과 같은 목적으로 사용됩니다:


1. 공통 인터페이스 정의: 추상 클래스는 하나 이상의 추상 메서드(abstract method)를 포함할 수 있습니다. 이 추상 메서드는 하위 클래스(subclass)에서 반드시 구현되어야 하는 메서드입니다. 이렇게 하면 추상 클래스는 하위 클래스에게 공통의 메서드 구현을 강제함으로써 일관된 인터페이스를 제공합니다.


2. 코드 재사용: 추상 클래스는 비슷한 특징을 가진 클래스 그룹에 대한 공통 로직을 제공하는 데 사용될 수 있습니다. 여러 클래스가 비슷한 동작을 공유할 때, 추상 클래스를 사용하여 중복 코드를 최소화하고 코드 재사용을 촉진할 수 있습니다.


3. 다형성(polymorphism) 지원: 추상 클래스는 다형성을 구현하는 데 도움이 됩니다. 추상 클래스를 기반으로 여러 하위 클래스를 만들고, 이들을 부모 클래스로 다루면, 다형성을 통해 다양한 하위 클래스를 동일한 인터페이스로 다룰 수 있습니다.


4. 추상 메서드 구현 강제: 추상 클래스의 추상 메서드는 하위 클래스에서 반드시 구현되어야 합니다. 이것은 개발자가 코드를 유지하고 확장할 때 필수 메서드를 놓치는 것을 방지하고 안정성을 향상시키는 데 도움이 됩니다.


5. 객체 지향 설계 원칙 준수: 추상 클래스는 객체 지향 설계 원칙 중 하나인 "추상화"를 지원합니다. 추상 클래스를 사용하면 실세계의 개념을 추상화하고 모델링할 수 있으며, 이는 더 나은 소프트웨어 구조와 유지 관리 용이성을 제공할 수 있습니다.


요약하면, 추상 클래스는 공통 인터페이스 정의, 코드 재사용, 다형성, 메서드 구현 강제, 객체 지향 설계 원칙 준수 등 다양한 목적으로 사용됩니다. 이는 객체 지향 소프트웨어 개발에서 중요한 도구 중 하나입니다.


Certainly! Here's an example of an abstract class with some business logic. In this example, we'll create an abstract class `Employee` to represent different types of employees in a company, such as managers and developers. Each type of employee will have its own implementation of calculating the salary.


```php

// Define an abstract class Employee
abstract class Employee {
    protected $name;
    protected $employeeId;
    public function __construct($name, $employeeId) {
        $this->name = $name;
        $this->employeeId = $employeeId;
    }
    // Declare an abstract method for calculating salary
    abstract public function calculateSalary();
}
// Create a subclass for Manager
class Manager extends Employee {
    private $baseSalary;
    private $bonus;
    public function __construct($name, $employeeId, $baseSalary, $bonus) {
        parent::__construct($name, $employeeId);
        $this->baseSalary = $baseSalary;
        $this->bonus = $bonus;
    }
    // Implement the abstract method to calculate the salary of a manager
    public function calculateSalary() {
        return $this->baseSalary + $this->bonus;
    }
}
// Create a subclass for Developer
class Developer extends Employee {
    private $hourlyRate;
    private $hoursWorked;
    public function __construct($name, $employeeId, $hourlyRate, $hoursWorked) {
        parent::__construct($name, $employeeId);
        $this->hourlyRate = $hourlyRate;
        $this->hoursWorked = $hoursWorked;
    }
    // Implement the abstract method to calculate the salary of a developer
    public function calculateSalary() {
        return $this->hourlyRate * $this->hoursWorked;
    }
}
// Create instances of Manager and Developer
$manager = new Manager("John Doe", "M123", 50000, 10000);
$developer = new Developer("Alice Smith", "D456", 30, 160);
// Calculate and display the salaries of the employees
echo "Manager {$manager->name}'s Salary: $" . $manager->calculateSalary() . PHP_EOL;
echo "Developer {$developer->name}'s Salary: $" . $developer->calculateSalary() . PHP_EOL;

```


In this PHP example:


1. We define an abstract class `Employee` with an abstract method `calculateSalary()`. Each subclass (e.g., `Manager` and `Developer`) must implement this method.

2. We create two subclasses, `Manager` and `Developer`, each with its own constructor and salary calculation method.

3. We create instances of the `Manager` and `Developer` subclasses, set their properties, and calculate their salaries by calling the `calculateSalary()` method.

This example demonstrates how abstract classes can be used to define a common interface for different types of employees while allowing each type of employee to have its own specific implementation of salary calculation logic.

Total 0

Total 45
Number Title Author Date Votes Views
40
php formatter
siwon | 2024.11.26 | Votes -1 | Views 1319
siwon 2024.11.26 -1 1319
39
html center 중앙정렬 tailwind
siwon | 2024.07.27 | Votes 0 | Views 1639
siwon 2024.07.27 0 1639
38
dropdown menu alpinejs 사용 버전
siwon | 2024.04.30 | Votes 0 | Views 1564
siwon 2024.04.30 0 1564
37
dropdown menu 간단 버전
siwon | 2024.04.30 | Votes 0 | Views 1522
siwon 2024.04.30 0 1522
36
The Standard PHP Library (SPL) is a collection of classes and interfaces that provide core functionality to PHP developers.
siwon | 2023.10.24 | Votes 0 | Views 2201
siwon 2023.10.24 0 2201
35
session 과 쿠키
siwon | 2023.10.24 | Votes 0 | Views 1461
siwon 2023.10.24 0 1461
34
Late Static Binding (LSB):메서드 내부에서 현재 클래스의 정적 메서드 또는 프로퍼티를 호출할 때 사용
siwon | 2023.10.24 | Votes 0 | Views 1284
siwon 2023.10.24 0 1284
33
PHP 예외 처리(Exception Handling)
siwon | 2023.10.10 | Votes 0 | Views 1605
siwon 2023.10.10 0 1605
32
php exception
siwon | 2023.10.10 | Votes 0 | Views 1802
siwon 2023.10.10 0 1802
31
예외(Exception)를 처리하기 위해 try...catch 블록을 사용하는 방법
siwon | 2023.10.10 | Votes 0 | Views 1339
siwon 2023.10.10 0 1339
30
Preserving Parent Class Functionality in overriding
siwon | 2023.09.26 | Votes 0 | Views 1173
siwon 2023.09.26 0 1173
29
oop 세부항목
siwon | 2023.09.26 | Votes 0 | Views 1189
siwon 2023.09.26 0 1189
28
method chaining
siwon | 2023.09.25 | Votes 0 | Views 1419
siwon 2023.09.25 0 1419
27
interface implements
siwon | 2023.09.19 | Votes 0 | Views 1242
siwon 2023.09.19 0 1242
Re:interface implements
siwon | 2023.10.24 | Votes 0 | Views 1049
siwon 2023.10.24 0 1049
26
abstract class : 부모 class로 사용되며 자식(extends 한)에게 abstract method를 강제함(그들만의 방식으로)
siwon | 2023.09.19 | Votes 0 | Views 1136
siwon 2023.09.19 0 1136
25
isset() / unset()
siwon | 2023.09.18 | Votes 0 | Views 1314
siwon 2023.09.18 0 1314
24
magic methods-어떤 상황이 되면 call 하지 않아도 자동으로 실행되는 메소드
siwon | 2023.09.18 | Votes 0 | Views 1321
siwon 2023.09.18 0 1321
23
MD(markdown) file
siwon | 2023.09.12 | Votes 0 | Views 1239
siwon 2023.09.12 0 1239
22
usort
siwon | 2023.08.30 | Votes 0 | Views 1277
siwon 2023.08.30 0 1277
21
closure=unanimous function
siwon | 2023.08.30 | Votes 0 | Views 1304
siwon 2023.08.30 0 1304
php 7.4에서 추가 화살표 함수 fn()=>
siwon | 2023.10.24 | Votes 0 | Views 3970
siwon 2023.10.24 0 3970
20
reference variable &
siwon | 2023.08.29 | Votes 0 | Views 1296
siwon 2023.08.29 0 1296
참조(reference)한 original variable의 값을 바꿔버리기 때문에 조심해서 써야함
siwon | 2023.08.30 | Votes 0 | Views 1226
siwon 2023.08.30 0 1226
19
PHP 변수 : 스칼라(Scalar), 복합(Composite), 그리고 리소스(Resource)
siwon | 2023.08.22 | Votes 0 | Views 1376
siwon 2023.08.22 0 1376
18
if : vs {}
siwon | 2023.08.22 | Votes 0 | Views 1120
siwon 2023.08.22 0 1120
17
null coalescing operator
siwon | 2023.08.18 | Votes 0 | Views 1467
siwon 2023.08.18 0 1467
16
arrary functions
siwon | 2023.08.18 | Votes 0 | Views 1281
siwon 2023.08.18 0 1281