נבנה על ידיBuilt by Ariel Yohimovich

JavaJava
19
חלקPart 4: OOP מתקדםAdvanced OOP כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

ירושה, super ו-overrideInheritance, super & override

extends, super() ו-super.method(), @Override, ומתי ירושה היא רעיון רע.

extends, super() and super.method(), @Override, and when inheritance is a bad idea.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.Try on your own before peeking. In the player use the arrow keys or the buttons. Each step shows where (file and line), what to write, and why.
תרגילExercise 1

חיות מדברותTalking animals

תזכורת: מה ביקשוReminder: the task

ל-Animal יש name, מתודה sound() שמחזירה ..., ו-describe() שמחזירה Rex says Woof. כתבו Dog ו-Cat שיורשות ודורסות רק את sound. הדפיסו Rex says Woof ו-Mitzi says Meow.

Animal has a name, a method sound() returning ..., and describe() returning Rex says Woof. Write Dog and Cat that extend it and override only sound. Print Rex says Woof and Mitzi says Meow.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    public static void main(String[] args) {
        Dog d = new Dog("Rex");
        Cat c = new Cat("Mitzi");
        System.out.println(d.describe());
        System.out.println(c.describe());
    }
}

class Animal {
    private final String name;

    Animal(String name) {
        this.name = name;
    }

    String getName() {
        return name;
    }

    String sound() {
        return "...";
    }

    String describe() {
        return getName() + " says " + sound();
    }
}

class Dog extends Animal {
    Dog(String name) {
        super(name);
    }

    @Override
    String sound() {
        return "Woof";
    }
}

class Cat extends Animal {
    Cat(String name) {
        super(name);
    }

    @Override
    String sound() {
        return "Meow";
    }
}
פלטOutput
Rex says Woof
Mitzi says Meow

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 2

מנהל עם בונוסA manager with a bonus

תזכורת: מה ביקשוReminder: the task

Manager extends Employee ומוסיפה bonus. דרסו את salary() כך שתחזיר את המשכורת של ההורה ועוד הבונוס, בלי לגשת ל-base (הוא private). הדפיסו Noa 10000 ו-Avi 15000.

Manager extends Employee and adds a bonus. Override salary() to return the parent's salary plus the bonus, without touching base (it's private). Print Noa 10000 and Avi 15000.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    public static void main(String[] args) {
        Employee e = new Employee("Noa", 10000);
        Manager m = new Manager("Avi", 12000, 3000);
        System.out.println(e.getName() + " " + e.salary());
        System.out.println(m.getName() + " " + m.salary());
    }
}

class Employee {
    private final String name;
    private final int base;

    Employee(String name, int base) {
        this.name = name;
        this.base = base;
    }

    String getName() {
        return name;
    }

    int salary() {
        return base;
    }
}

class Manager extends Employee {
    private final int bonus;

    Manager(String name, int base, int bonus) {
        super(name, base);
        this.bonus = bonus;
    }

    @Override
    int salary() {
        return super.salary() + bonus;
    }
}
פלטOutput
Noa 10000
Avi 15000

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 3

צייד באגים: super חסרBug hunter: a missing super

תזכורת: מה ביקשוReminder: the task

התוכנית מהתזכורת לא מתקמפלת. תקנו את הבנאי של EBook כך שיקרא ל-super("Untitled"), ויודפס Untitled.

The program from the refresher doesn't compile. Fix EBook's constructor to call super("Untitled"), so it prints Untitled.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println(new EBook(2).describe());
    }
}

class Book {
    final String title;

    Book(String title) {
        this.title = title;
    }

    String describe() {
        return title;
    }
}

class EBook extends Book {
    final int sizeMb;

    EBook(int sizeMb) {
        super("Untitled");
        this.sizeMb = sizeMb;
    }
}
פלטOutput
Untitled

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 4

צייד באגים: הדריסה שלא קרתהBug hunter: the override that never happened

תזכורת: מה ביקשוReminder: the task

התוכנית מדפיסה Book: Dune במקום EBook: Dune (2 MB). הוסיפו @Override מעל המתודה ב-EBook, קראו מה javac אומר, ותקנו.

The program prints Book: Dune instead of EBook: Dune (2 MB). Add @Override above the method in EBook, read what javac says, and fix it.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    public static void main(String[] args) {
        Book b = new EBook("Dune", 2);
        System.out.println(b.describe());
    }
}

class Book {
    final String title;

    Book(String title) {
        this.title = title;
    }

    String describe() {
        return "Book: " + title;
    }
}

class EBook extends Book {
    final int sizeMb;

    EBook(String title, int sizeMb) {
        super(title);
        this.sizeMb = sizeMb;
    }

    @Override
    String describe() {
        return "EBook: " + title + " (" + sizeMb + " MB)";
    }
}
פלטOutput
EBook: Dune (2 MB)

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 5

מי נבנה קודם?Who's built first?

תזכורת: מה ביקשוReminder: the task

שלוש מחלקות: C extends B, B extends A. כל בנאי מדפיס את השם שלו עם print. new C() מדפיס A B C. כתבו וצפו בסימולציה.

Three classes: C extends B, B extends A. Each constructor prints its name with print. new C() prints A B C. Write it and watch the simulation.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    public static void main(String[] args) {
        new C();
        System.out.println();
    }
}

class A {
    A() {
        System.out.print("A ");
    }
}

class B extends A {
    B() {
        System.out.print("B ");
    }
}

class C extends B {
    C() {
        System.out.print("C");
    }
}
פלטOutput
A B C

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 6

מדף, צעד 19: EBook ו-AudioBookShelf, step 19: EBook and AudioBook

תזכורת: מה ביקשוReminder: the task

Book(title, author) עם describe() (Emma by Austen). EBook מוסיפה גודל (Dune by Herbert [ebook, 2 MB]), ו-AudioBook מוסיפה דקות (Ulysses by Joyce [audio, 1h 30m]). שתיהן משתמשות ב-super.describe(). הדפיסו את שלושתם.

Book(title, author) with describe() (Emma by Austen). EBook adds a size (Dune by Herbert [ebook, 2 MB]), and AudioBook adds minutes (Ulysses by Joyce [audio, 1h 30m]). Both use super.describe(). Print all three.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    public static void main(String[] args) {
        Book b = new Book("Emma", "Austen");
        EBook e = new EBook("Dune", "Herbert", 2);
        AudioBook a = new AudioBook("Ulysses", "Joyce", 90);
        System.out.println(b.describe());
        System.out.println(e.describe());
        System.out.println(a.describe());
    }
}

class Book {
    private final String title;
    private final String author;

    Book(String title, String author) {
        this.title = title;
        this.author = author;
    }

    String describe() {
        return title + " by " + author;
    }
}

class EBook extends Book {
    private final int sizeMb;

    EBook(String title, String author, int sizeMb) {
        super(title, author);
        this.sizeMb = sizeMb;
    }

    @Override
    String describe() {
        return super.describe() + " [ebook, " + sizeMb + " MB]";
    }
}

class AudioBook extends Book {
    private final int minutes;

    AudioBook(String title, String author, int minutes) {
        super(title, author);
        this.minutes = minutes;
    }

    @Override
    String describe() {
        return super.describe() + " [audio, " + minutes / 60 + "h " + minutes % 60 + "m]";
    }
}
פלטOutput
Emma by Austen
Dune by Herbert [ebook, 2 MB]
Ulysses by Joyce [audio, 1h 30m]

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 1

מחסנית עם הרכבהA stack with composition

תזכורת: מה ביקשוReminder: the task

כתבו מחדש את Stack מהתזכורת בלי ירושה: שדה private final List<Integer> items, ורק push, pop, peek ו-size. דחפו 1, 2, 3 והדפיסו 3 2 2 (pop, peek, size).

Rewrite Stack from the refresher without inheritance: a field private final List<Integer> items, and only push, pop, peek and size. Push 1, 2, 3 and print 3 2 2 (pop, peek, size).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Stack s = new Stack();
        s.push(1);
        s.push(2);
        s.push(3);
        System.out.println(s.pop() + " " + s.peek() + " " + s.size());
    }
}

class Stack {
    private final List<Integer> items = new ArrayList<>();

    void push(int x) {
        items.add(x);
    }

    int pop() {
        return items.remove(items.size() - 1);
    }

    int peek() {
        return items.get(items.size() - 1);
    }

    int size() {
        return items.size();
    }
}
פלטOutput
3 2 2

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 2

חיסכון עם מינימוםSavings with a minimum

תזכורת: מה ביקשוReminder: the task

ל-Account יש protected int balance ו-withdraw. Savings דורסת את withdraw כך שהיתרה לא תרד מתחת ל-MINIMUM = 100 (ואז קוראת ל-super.withdraw), ומוסיפה addInterest() של 10%. מ-500: משכו 300 (true 200), ואז 150 (false 200), ואז ריבית (220).

Account has protected int balance and withdraw. Savings overrides withdraw so the balance never goes below MINIMUM = 100 (then calls super.withdraw), and adds addInterest() of 10%. From 500: withdraw 300 (true 200), then 150 (false 200), then interest (220).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    public static void main(String[] args) {
        Savings s = new Savings(500);
        System.out.println(s.withdraw(300) + " " + s.getBalance());
        System.out.println(s.withdraw(150) + " " + s.getBalance());
        s.addInterest();
        System.out.println(s.getBalance());
    }
}

class Account {
    protected int balance;

    Account(int balance) {
        this.balance = balance;
    }

    int getBalance() {
        return balance;
    }

    boolean withdraw(int amount) {
        if (amount > balance) {
            return false;
        }
        balance -= amount;
        return true;
    }
}

class Savings extends Account {
    static final int MINIMUM = 100;

    Savings(int balance) {
        super(balance);
    }

    @Override
    boolean withdraw(int amount) {
        if (balance - amount < MINIMUM) {
            return false;
        }
        return super.withdraw(amount);
    }

    void addInterest() {
        balance += balance / 10;
    }
}
פלטOutput
true 200
false 200
220

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

נבנה על ידיBuilt by Ariel Yohimovich