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

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

abstract ו-interfacesabstract & interfaces

מחלקות מופשטות, interfaces עם default ו-static methods, ומימוש של כמה interfaces.

Abstract classes, interfaces with default and static methods, and implementing several interfaces.

01המונחים של המפגשThis session's terms

לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.

Before the code, the words. Every term here is also linked in the course glossary.

  • מחלקה מופשטת: abstract class Shape: אי אפשר ליצור ממנה עצם (new Shape() לא מתקמפל), רק לרשת ממנה. יכולה להחזיק שדות, בנאים וקוד משותף.abstract class: abstract class Shape: you can't make an object of it (new Shape() doesn't compile), only extend it. It can hold fields, constructors and shared code.
  • מתודה מופשטת: abstract double area();: כותרת בלי גוף. כל תת-מחלקה לא מופשטת חייבת לממש אותה, אחרת javac עוצר.abstract method: abstract double area();: a header with no body. Every non-abstract subclass must implement it, or javac stops.
  • interface: חוזה: רשימת מתודות שמחלקה מבטיחה לממש (implements). מחלקה יכולה לממש כמה interfaces. אין בו שדות של עצם.interface: A contract: a list of methods a class promises to implement (implements). A class can implement several interfaces. It has no object fields.
  • מתודת default: מתודה עם גוף בתוך interface. כל מי שמממש מקבל אותה, ויכול לדרוס. היא בנויה מהמתודות האחרות של ה-interface.default method: A method with a body inside an interface. Every implementer gets it, and can override it. It's built from the interface's other methods.
  • Comparable: Comparable<T> מגדיר "סדר טבעי": compareTo מחזיר מספר שלילי, 0 או חיובי. Arrays.sort ו-Collections.sort משתמשים בו.Comparable: Comparable<T> defines a "natural order": compareTo returns a negative number, 0 or a positive one. Arrays.sort and Collections.sort use it.
  • Template Method: מתודה בהורה (לרוב final) שקובעת את סדר השלבים, ומשאירה שלבים מופשטים לתת-המחלקות.Template Method: A method in the parent (often final) that fixes the order of the steps, leaving abstract steps to the subclasses.

02מחלקה מופשטת: תבנית חלקיתAn abstract class: a partial blueprint

ל-Shape אין דרך לחשב שטח, ולכן area מופשטת. describe כתובה פעם אחת בהורה, ובזמן ריצה קוראת ל-area של העצם האמיתי (עיגול או ריבוע).

Shape has no way to compute an area, so area is abstract. describe is written once in the parent, and at run time it calls the real object's area (circle or square).

Main.java
public class Main {
    public static void main(String[] args) {
        Shape c = new Circle(1);
        Shape s = new Square(2);
        System.out.println(c.describe());
        System.out.println(s.describe());
    }
}

abstract class Shape {
    abstract double area();

    abstract String name();

    String describe() {
        return name() + " with area " + String.format("%.2f", area());
    }
}

class Circle extends Shape {
    private final double r;

    Circle(double r) {
        this.r = r;
    }

    @Override
    double area() {
        return Math.PI * r * r;
    }

    @Override
    String name() {
        return "Circle";
    }
}

class Square extends Shape {
    private final double side;

    Square(double side) {
        this.side = side;
    }

    @Override
    double area() {
        return side * side;
    }

    @Override
    String name() {
        return "Square";
    }
}
פלטOutput
Circle with area 3.14
Square with area 4.00
צפו בהרצה צעד אחר צעד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

03אי אפשר ליצור עצם מופשטYou can't create an abstract object

new Shape() לא מתקמפל: מה היה השטח שלו?

new Shape() doesn't compile: what would its area be?

טעות נפוצהCommon mistake

אי אפשר ליצור עצם מופשט

You can't create an abstract object

Main.java
public class Main {
    public static void main(String[] args) {
        Shape s = new Shape();
    }
}

abstract class Shape {
    abstract double area();
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:3: error: Shape is abstract; cannot be instantiated
        Shape s = new Shape();
                  ^
1 error
בעברית פשוטה: In plain words: Shape is abstract; cannot be instantiated: יוצרים Circle או Square, לא Shape.Shape is abstract; cannot be instantiated: create a Circle or a Square, not a Shape.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

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

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

מסך הפלטOutput screen

04interface, default, וכמה interfacesinterface, default, and several interfaces

Duck מממשת שני interfaces. מ-Flyer היא מקבלת את describe (מתודת default) בחינם. משתנה מסוג Flyer רואה רק את מה ש-Flyer מבטיח. מתודות שמממשות interface חייבות להיות public.

Duck implements two interfaces. From Flyer it gets describe (a default method) for free. A variable of type Flyer sees only what Flyer promises. Methods implementing an interface must be public.

Main.java
public class Main {
    public static void main(String[] args) {
        Duck d = new Duck();
        System.out.println(d.fly() + ", " + d.swim());
        System.out.println(d.describe());
        Flyer f = d;
        System.out.println(f.fly());
    }
}

interface Flyer {
    String fly();

    default String describe() {
        return "I can " + fly();
    }
}

interface Swimmer {
    String swim();
}

class Duck implements Flyer, Swimmer {
    @Override
    public String fly() {
        return "fly low";
    }

    @Override
    public String swim() {
        return "paddle";
    }
}
פלטOutput
fly low, paddle
I can fly low
fly low
צפו בהרצה צעד אחר צעד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

05טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says

אלה הטעויות שהתרגילים מהסוג "צייד באגים" בנויים סביבן. כל אחת רצה באמת, והפלט הוא מה ש-Java עונה.

These are the mistakes the "bug hunter" exercises are built around. Each one really runs, and the output is what Java says.

טעות נפוצהCommon mistake

צייד באגים: שכחו לממש

Bug hunter: forgot to implement

Main.java
public class Main {
    public static void main(String[] args) {
        Shape c = new Circle(2);
        System.out.println(String.format("%.2f", c.area()));
    }
}

abstract class Shape {
    abstract double area();
}

class Circle extends Shape {
    private final double r;

    Circle(double r) {
        this.r = r;
    }
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:12: error: Circle is not abstract and does not override abstract method area() in Shape
class Circle extends Shape {
^
1 error
בעברית פשוטה: In plain words: Circle is not abstract and does not override abstract method area() in Shape: חסר מימוש של area.Circle is not abstract and does not override abstract method area() in Shape: area has no implementation.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

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

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

מסך הפלטOutput screen

06הצעד של היום בפרויקט מדףToday's step in the Shelf project

interface Lendable עם name(), borrower(), lendTo, giveBack ו-default String status() (Dune: lent to Noa או DVD Alien: available). Book ו-Dvd מממשות. השאילו את Dune ל-Noa, הדפיסו את המצב של שניהם, החזירו, והדפיסו שוב את Dune.

interface Lendable with name(), borrower(), lendTo, giveBack and default String status() (Dune: lent to Noa or DVD Alien: available). Book and Dvd implement it. Lend Dune to Noa, print both statuses, give it back, and print Dune again.

טיפTip

את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.

You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

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