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

JavaJava

מבחן 4: OOP מתקדםExam 4: Advanced OOP

ירושה, ממשקים, פולימורפיזם, Generics, records, sealed ו-pattern matching

Inheritance, interfaces, polymorphism, generics, records, sealed types and pattern matching

75 דקותminutes4 שאלות בחירהmultiple choice3 שאלות קודcoding questions100 נקודותpoints
75:00השעון רק עוזר להתאמן. אפשר גם בלי.The timer is just for practice. You can skip it.

חלק א: שאלות בחירה (5 נקודות לשאלה)Part A: multiple choice (5 points each)

התשובות מתגלות רק כשמסיימים את המבחן.Answers are revealed only when you finish the exam.

1. מה יודפס?What is printed? 5
java
static class Animal {
    String sound() {
        return "...";
    }
}

static class Dog extends Animal {
    @Override
    String sound() {
        return "Woof";
    }
}

Animal a = new Dog();
System.out.println(a.sound());
2. מה יודפס?What is printed? 5
java
record P(int x, int y) {
}

System.out.println(new P(1, 2));
3. מה javac יגיד על השורה הזאת?What will javac say about this line? 5
java
List<Object> objs = new ArrayList<String>();
4. ב-switch על sealed interface עם כל המימושים, למה לא צריך default?In a switch over a sealed interface that covers every implementation, why is no default needed? 5

חלק ב: שאלות קודPart B: coding questions

שאלהQuestion 5

שטח כוללTotal area

abstract class Shape עם abstract double area(), ושתי מחלקות: Circle(r) ו-Rect(w, h). כתבו static double totalArea(List<Shape> shapes) שמחזירה סכום מעוגל לשתי ספרות. main מדפיס 15.14.

An abstract class Shape with abstract double area(), and two classes: Circle(r) and Rect(w, h). Write static double totalArea(List<Shape> shapes) returning the sum rounded to two decimals. main prints 15.14.

איך הפלט אמור להיראות?What should the output look like?
15.14
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: Math.PI * r * r.Math.PI * r * r.
רמזHint 2: Math.round(sum * 100) / 100.0.Math.round(sum * 100) / 100.0.
הפתרון שלנוOur solution
Main.java
import java.util.List;

public class Main {
    static double totalArea(List<Shape> shapes) {
        double sum = 0;
        for (Shape s : shapes) {
            sum += s.area();
        }
        return Math.round(sum * 100) / 100.0;
    }

    public static void main(String[] args) {
        System.out.println(totalArea(List.of(new Circle(1), new Rect(3, 4))));
    }
}

abstract class Shape {
    abstract double area();
}

class Circle extends Shape {
    private final double r;

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

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

class Rect extends Shape {
    private final double w;
    private final double h;

    Rect(double w, double h) {
        this.w = w;
        this.h = h;
    }

    double area() {
        return w * h;
    }
}
פלטOutput
15.14

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.

מחווןRubric (25 נקודותpoints)

כשכל הבדיקות עוברות, כל השורות מסומנות. אם לא, סמנו בעצמכם מה כן עשיתם נכון.When every check passes, all rows are ticked. If not, tick what you did get right.

שאלהQuestion 6

מחסנית גנריתA generic stack

כתבו class Stack<T> עם push(T), pop(), peek() ו-isEmpty(). pop ו-peek על מחסנית ריקה זורקות IllegalStateException. main מדפיס c b false.

Write class Stack<T> with push(T), pop(), peek() and isEmpty(). pop and peek on an empty stack throw IllegalStateException. main prints c b false.

איך הפלט אמור להיראות?What should the output look like?
c b false
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: ArrayList<T> בפנים, והאיבר העליון בסוף.An ArrayList<T> inside, with the top item at the end.
הפתרון שלנוOur solution
Main.java
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Stack<String> s = new Stack<>();
        s.push("a");
        s.push("b");
        s.push("c");
        String top = s.pop();
        System.out.println(top + " " + s.peek() + " " + s.isEmpty());
    }
}

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

    void push(T item) {
        items.add(item);
    }

    T pop() {
        if (items.isEmpty()) {
            throw new IllegalStateException("empty stack");
        }
        return items.remove(items.size() - 1);
    }

    T peek() {
        if (items.isEmpty()) {
            throw new IllegalStateException("empty stack");
        }
        return items.get(items.size() - 1);
    }

    boolean isEmpty() {
        return items.isEmpty();
    }
}
פלטOutput
c b false

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.

מחווןRubric (25 נקודותpoints)

כשכל הבדיקות עוברות, כל השורות מסומנות. אם לא, סמנו בעצמכם מה כן עשיתם נכון.When every check passes, all rows are ticked. If not, tick what you did get right.

שאלהQuestion 7

רובוט פקודותA command robot

sealed interface Command עם Move(int steps), Turn(boolean right) ו-Stop(). הרובוט מתחיל ב-(0, 0) מול צפון. כתבו static String run(List<Command> cmds): Move זז בכיוון הנוכחי (צפון מגדיל y, מזרח מגדיל x), Turn מסתובב 90°, ו-Stop עוצר (מתעלמים מהשאר). החזירו x,y facing D כש-D אחד מ-N, E, S, W. בלי default.

A sealed interface Command with Move(int steps), Turn(boolean right) and Stop(). The robot starts at (0, 0) facing north. Write static String run(List<Command> cmds): Move goes in the current direction (north grows y, east grows x), Turn rotates 90°, and Stop halts (ignore the rest). Return x,y facing D where D is one of N, E, S, W. No default.

איך הפלט אמור להיראות?What should the output look like?
2,-2 facing S
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: כיוון כמספר 0–3, ו-"NESW".charAt(dir).The direction as a number 0–3, and "NESW".charAt(dir).
רמזHint 2: פנייה שמאלה: (dir + 3) % 4.A left turn: (dir + 3) % 4.
הפתרון שלנוOur solution
Main.java
import java.util.List;

public class Main {
    static String run(List<Command> cmds) {
        int x = 0;
        int y = 0;
        int dir = 0;
        int[] dx = {0, 1, 0, -1};
        int[] dy = {1, 0, -1, 0};
        for (Command c : cmds) {
            boolean stop = false;
            switch (c) {
                case Move(int steps) -> {
                    x += dx[dir] * steps;
                    y += dy[dir] * steps;
                }
                case Turn(boolean right) -> dir = right ? (dir + 1) % 4 : (dir + 3) % 4;
                case Stop() -> stop = true;
            }
            if (stop) {
                break;
            }
        }
        return x + "," + y + " facing " + "NESW".charAt(dir);
    }

    public static void main(String[] args) {
        System.out.println(run(List.of(new Move(3), new Turn(true), new Move(2), new Turn(true), new Move(5), new Stop(), new Move(100))));
    }
}

sealed interface Command permits Move, Turn, Stop {
}

record Move(int steps) implements Command {
}

record Turn(boolean right) implements Command {
}

record Stop() implements Command {
}
פלטOutput
2,-2 facing S

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.

מחווןRubric (30 נקודותpoints)

כשכל הבדיקות עוברות, כל השורות מסומנות. אם לא, סמנו בעצמכם מה כן עשיתם נכון.When every check passes, all rows are ticked. If not, tick what you did get right.

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