PHP 가 내는 오류Fatal error: Class TinyLot contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (ParkingLot::ratePer30Min)
고친 코드
abstractclassParkingLot{abstractprotectedfunctionratePer30Min(): int;publicfunctionhour(): int {return$this->ratePer30Min() * 2; }}finalclassTinyLotextendsParkingLot{protectedfunctionratePer30Min(): int {return700; }}echo (newTinyLot())->hour(), "\n";
실행하면1400
추상 메서드에 몸통을 적음
abstract 는 "몸통은 자식이 적는다"는 뜻이라 중괄호를 붙일 수 없어요. 기본값을 주고 싶다면 abstract 를 빼고 보통 메서드로 적어 자식이 필요할 때만 덮어쓰게 해요.
틀린 코드
abstractclassParkingLot{abstractprotectedfunctionratePer30Min(): int {return0; }}
PHP 가 내는 오류Fatal error: Abstract function ParkingLot::ratePer30Min() cannot contain body
고친 코드
abstractclassParkingLot{protectedfunctionratePer30Min(): int {return0; }}finalclassFreeLotextendsParkingLot{publicfunctionrate(): int {return$this->ratePer30Min(); }}echo (newFreeLot())->rate(), "\n";
실행하면0
자식에서 공개 범위를 더 좁힘
부모가 protected 로 정한 메서드를 자식이 private 으로 줄이면 부모의 fee() 가 부를 수 없게 돼요. 덮어쓸 때 공개 범위는 같게 두거나 더 넓혀요(protected → public).
틀린 코드
abstractclassParkingLot{abstractprotectedfunctionratePer30Min(): int;}finalclassMiniLotextendsParkingLot{privatefunctionratePer30Min(): int {return500; }}
PHP 가 내는 오류Fatal error: Access level to MiniLot::ratePer30Min() must be protected (as in class ParkingLot) or weaker
답: 1. 0 쇼핑몰은 처음 60분이 무료라 돈을 낼 시간이 0분이에요. 0칸 x 1000원 = 0원이에요.
문제 2
인터페이스 대신 추상 클래스를 고르기 좋은 때는?
답과 까닭 보기
답: 3. 계산 순서와 공통 코드는 부모가 쥐고 일부만 자식이 채워야 할 때 추상 클래스는 몸통 있는 메서드(fee())와 빈칸(ratePer30Min())을 함께 가질 수 있어요. 순서를 부모가 정하고 숫자만 자식이 넣는 꼴에 맞아요. 약속만 필요하면 인터페이스가 더 가벼워요.
자주 묻는 것
추상 클래스로 객체를 만들 수 있나요?
아니요. new 하면 Cannot instantiate abstract class 오류가 나요. 빈칸을 채운 자식 클래스로 만들어요.
추상 클래스와 인터페이스 중 무엇을 고르나요?
공통 코드와 순서를 부모가 쥐어야 하면 추상 클래스, 약속만 정하면 인터페이스예요. 둘을 같이 사용하기도 해요.
trait 는 추상 클래스 대신 사용할 수 있나요?
trait 는 코드를 붙여 넣는 조각이라 자료형으로 사용할 수 없어요. 약속은 인터페이스, 붙일 코드는 trait 로 나눠요.