Lesson 4 / الدرس 4

Inheritance / الوراثة

One class built on another, so the shared part is written once. It is the most taught idea in object-oriented programming and the most overused, so this lesson teaches both halves.

صنف مبني على آخر ليُكتب الجزء المشترك مرة. وهي أكثر أفكار البرمجة الكائنية تدريسًا وأكثرها إفراطًا في الاستعمال، فيعلّم هذا الدرس النصفين.

The shared part, written once

class Room { }                        the parent, or base class
class Suite extends Room { }          the child, or subclass

super(...)      call the parent's constructor — before using this
super.method()  call the parent's version of a method you replaced

PHP    class Suite extends Room { parent::__construct(...) }
Dart   class Suite extends Room { Suite(...) : super(...) }
The demonstration has three kinds of room that agree on almost everything and differ in how the price is worked out. Read what each subclass had to write: a constructor line and one method. Everything else came down from the parent.

The question to ask before extending

Inheritance says is a, not has a and not is a bit like. A suite is a room, so anywhere the program expects a room it can be handed a suite and nothing breaks — that is the whole promise, and it is what makes describe() work for all three. Say the sentence out loud before you write extends. "A booking is a customer" is nonsense, and the code built on it will be too.

SentenceVerdict
A suite is a roomInheritance fits
A booking has a guestA property, not a parent
An admin is a userFits — if an admin can go everywhere a user can
A square is a rectangleFamously not, once either can be resized
A PDF invoice is an invoiceFits, if only the rendering differs
A cart is a list of itemsUsually has a list rather than is one

The fourth row is worth a minute. A square is a rectangle in geometry; in code, a Rectangle with setWidth and setHeight promises those are independent, and a Square cannot keep that promise. When a subclass has to break something the parent guaranteed, the relationship is wrong however true the English sentence sounds.

Two mechanics worth knowing. super(...) in a constructor must run before you touch this, because until the parent has finished there is no object to touch — JavaScript throws a plain ReferenceError if you forget, and it is one of the clearer messages in the language. And super.priceFor() lets a subclass build on the parent's answer instead of replacing it, which is what LongStayRoom does — usually the better of the two, because it keeps one copy of the underlying rule.

Try it live / جرّب بنفسك

Preview / المعاينة

Check yourself / اختبر نفسك

1. What relationship does extends claim?

2. Why is a Square extending a Rectangle a problem?

3. What is the risk of four levels of inheritance?

Your task / مهمتك

Build a base class and two subclasses where one subclass replaces a method outright and the other calls super and adjusts the answer. Show a method written once in the parent working for all three. Then write down three "X is a Y" sentences from a system you know, decide for each whether inheritance fits, and say why in one line — including at least one where the answer is no.

ابنِ صنفًا أساسًا وصنفين فرعيين، يستبدل أحدهما طريقة كليًا ويستدعي الآخر super ويعدّل الجواب. وأظهر طريقة مكتوبة مرة في الأب تعمل للثلاثة. ثم اكتب ثلاث جمل "س هو ص" من نظام تعرفه، وقرر لكل واحدة هل تناسبها الوراثة، وقل لماذا في سطر — على أن تكون واحدة منها على الأقل إجابتها لا.

  • A parent and two subclasses أب وصنفان فرعيان
  • One override that replaces, one that calls super تجاوز يستبدل وآخر يستدعي super
  • A parent method working for every subclass طريقة من الأب تعمل لكل صنف فرعي
  • Three "is a" sentences judged, at least one rejected ثلاث جمل "هو" محكوم عليها وواحدة مرفوضة
How do you want to submit? / كيف تريد التسليم؟