انتقل للمحتوى
Robo EgyptRobo Egypt
تقدّمك في الجزء0 من 24
الدرس 3.2 · الكود والأرقام⏱ 12 دقيقة
الفصل 3: Inheritance و Polymorphism: نفس الأمر، تنفيذ مختلف

تجربة: الإجمالي من غير if

3 أنواع كورسات، والكود اللي بيحسب الإجمالي مايعرفش ولا نوع.

  • Scratch 800، و Python 1800، و Robotics 2000 = 4600.
  • نسيت تكتب السعر في نوع جديد؟ الـ compile فشل.
  • الـ JVM بتختار الـ method الصح وقت التشغيل (vtable).

الشرح بالتفصيل

import java.util.List;

abstract class Course {
    protected final String title;
    protected final int sessions;
    Course(String title, int sessions) { this.title = title; this.sessions = sessions; }
    abstract double pricePerSession();                       // كل نوع يقرر
    double price() { return sessions * pricePerSession(); }  // الشكل العام واحد
    public String toString() { return String.format("%-10s %6.0f EGP", title, price()); }
}
class ScratchCourse extends Course {
    ScratchCourse() { super("Scratch", 8); }
    double pricePerSession() { return 100; }
}
class PythonCourse extends Course {
    PythonCourse() { super("Python", 12); }
    double pricePerSession() { return 150; }
}
class RoboticsCourse extends Course {
    RoboticsCourse() { super("Robotics", 10); }
    double pricePerSession() { return 150 + 50; }            // + خامات الكيت
}

public class Courses {
    public static void main(String[] a) {
        List<Course> all = List.of(new ScratchCourse(), new PythonCourse(), new RoboticsCourse());
        double total = 0;
        for (Course c : all) {                               // الكود ده مش عارف ولا نوع
            System.out.println(c);
            total += c.price();
        }
        System.out.printf("total      %6.0f EGP%n", total);
    }
}
النتيجة:
Scratch       800 EGP
Python       1800 EGP
Robotics     2000 EGP
total        4600 EGP

ولو ضفت AIKidsCourse extends Course ونسيت تكتب pricePerSession؟ البرنامج مش هيتعمله compile: AIKidsCourse is not abstract and does not override abstract method pricePerSession() in Course. النسيان اللي طبع «None+» في الفصل 1 بقى مستحيل.

شكل 9.2 · إزاي c.pricePerSession() بتعرف تنادي أنهي نسخة: كل class ليه جدول دوال (vtable)، وكل object بيشاور على الـ class بتاعه.
شكل 9.2 · إزاي c.pricePerSession() بتعرف تنادي أنهي نسخة: كل class ليه جدول دوال (vtable)، وكل object بيشاور على الـ class بتاعه.
ملاحظةدوس «☕ افتح في روبو كود» وشغّل الكود في المتصفح وغيّر فيه. وفي برنامج روبو لاب على الكمبيوتر فيه كمان «🖥 شغّل على الجهاز» على Java الحقيقية (JVM).
خلصت الدرس؟ علّم عليه عشان تقدّمك يتحسب.