פולימורפיזם ו-dynamic dispatchPolymorphism & dynamic dispatch
הפניה מטיפוס אחד ועצם מטיפוס אחר, איזו מתודה נבחרת בזמן ריצה, casting ו-instanceof.
A reference of one type and an object of another, which method is chosen at run time, casting and instanceof.
סך כל השטחיםTotal area
תזכורת: מה ביקשוReminder: the task
במערך Shape[] יש שני עיגולים (רדיוס 1 ו-2) ומלבן 2x3. חשבו בלולאה אחת את סך השטחים והדפיסו Total: 21.71.
A Shape[] array holds two circles (radius 1 and 2) and a 2x3 rectangle. Compute the total area in one loop and print Total: 21.71.
סימולציה: הפתרון רץ שורה אחרי שורה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
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
public static void main(String[] args) {
Shape[] shapes = {new Circle(1), new Rect(2, 3), new Circle(2)};
double total = 0;
for (Shape s : shapes) {
total += s.area();
}
System.out.println(String.format("Total: %.2f", total));
}
}
abstract class Shape {
abstract double area();
}
class Circle extends Shape {
private final double r;
Circle(double r) {
this.r = r;
}
@Override
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;
}
@Override
double area() {
return w * h;
}
}Total: 21.71
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
גן חיותA zoo
תזכורת: מה ביקשוReminder: the task
מערך של Animal עם כלב, חתול וכלב. הדפיסו את כל הקולות בשורה אחת (Woof Meow Woof), ואחר כך Dogs: 2 (ספירה עם instanceof).
An Animal array with a dog, a cat and a dog. Print all the sounds on one line (Woof Meow Woof), then Dogs: 2 (counted with instanceof).
סימולציה: הפתרון רץ שורה אחרי שורה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
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
public static void main(String[] args) {
Animal[] zoo = {new Dog(), new Cat(), new Dog()};
int dogs = 0;
for (Animal a : zoo) {
System.out.print(a.sound() + " ");
if (a instanceof Dog) {
dogs++;
}
}
System.out.println();
System.out.println("Dogs: " + dogs);
}
}
abstract class Animal {
abstract String sound();
}
class Dog extends Animal {
@Override
String sound() {
return "Woof";
}
}
class Cat extends Animal {
@Override
String sound() {
return "Meow";
}
}Woof Meow Woof Dogs: 2
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
צייד באגים: המרה עיוורתBug hunter: a blind cast
תזכורת: מה ביקשוReminder: the task
התוכנית סוכמת את הגודל של הספרים הדיגיטליים, וקורסת על ה-DVD. תקנו עם instanceof כך שיודפס Total: 2 MB.
The program sums the sizes of the ebooks, and crashes on the DVD. Fix it with instanceof so it prints Total: 2 MB.
סימולציה: הפתרון רץ שורה אחרי שורה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
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
public static void main(String[] args) {
Item[] items = {new EBook("Dune", 2), new Dvd("Alien")};
int total = 0;
for (Item it : items) {
if (it instanceof EBook e) {
total += e.getSizeMb();
}
}
System.out.println("Total: " + total + " MB");
}
}
class Item {
protected final String title;
Item(String title) {
this.title = title;
}
String kind() {
return "item";
}
int loanDays() {
return 14;
}
String line() {
return title + " (" + kind() + ", " + loanDays() + " days)";
}
}
class EBook extends Item {
private final int sizeMb;
EBook(String title, int sizeMb) {
super(title);
this.sizeMb = sizeMb;
}
int getSizeMb() {
return sizeMb;
}
@Override
String kind() {
return "ebook";
}
@Override
int loanDays() {
return 21;
}
}
class Dvd extends Item {
Dvd(String title) {
super(title);
}
@Override
String kind() {
return "dvd";
}
@Override
int loanDays() {
return 3;
}
}Total: 2 MB
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
overloading ו-overriding יחדOverloading and overriding together
תזכורת: מה ביקשוReminder: the task
ל-Greeter יש שתי גרסאות של greet (עם String ועם int). LoudGreeter דורסת רק את גרסת ה-String. עם Greeter g = new LoudGreeter(), הדפיסו g.greet("Noa") ו-g.greet(3): HI NOA! ואז HiHiHi.
Greeter has two versions of greet (with a String and with an int). LoudGreeter overrides only the String one. With Greeter g = new LoudGreeter(), print g.greet("Noa") and g.greet(3): HI NOA! then HiHiHi.
סימולציה: הפתרון רץ שורה אחרי שורה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
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
public static void main(String[] args) {
Greeter g = new LoudGreeter();
System.out.println(g.greet("Noa"));
System.out.println(g.greet(3));
}
}
class Greeter {
String greet(String name) {
return "Hi " + name;
}
String greet(int times) {
return "Hi".repeat(times);
}
}
class LoudGreeter extends Greeter {
@Override
String greet(String name) {
return "HI " + name.toUpperCase() + "!";
}
}HI NOA! HiHiHi
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מתודה שמקבלת את ההורהA method that takes the parent
תזכורת: מה ביקשוReminder: the task
כתבו static int maxLoan(Item[] items) ו-static int minLoan(Item[] items). הן לא יודעות אילו סוגים יש במערך. עבור Emma, Dune (ebook) ושני DVD, הדפיסו Longest: 21 ו-Shortest: 3.
Write static int maxLoan(Item[] items) and static int minLoan(Item[] items). They don't know which kinds are in the array. For Emma, Dune (ebook) and two DVDs, print Longest: 21 and Shortest: 3.
סימולציה: הפתרון רץ שורה אחרי שורה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
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
static int maxLoan(Item[] items) {
int best = 0;
for (Item it : items) {
best = Math.max(best, it.loanDays());
}
return best;
}
static int minLoan(Item[] items) {
int best = Integer.MAX_VALUE;
for (Item it : items) {
best = Math.min(best, it.loanDays());
}
return best;
}
public static void main(String[] args) {
Item[] items = {new Item("Emma"), new EBook("Dune", 2), new Dvd("Alien"), new Dvd("Heat")};
System.out.println("Longest: " + maxLoan(items));
System.out.println("Shortest: " + minLoan(items));
}
}
class Item {
protected final String title;
Item(String title) {
this.title = title;
}
String kind() {
return "item";
}
int loanDays() {
return 14;
}
String line() {
return title + " (" + kind() + ", " + loanDays() + " days)";
}
}
class EBook extends Item {
private final int sizeMb;
EBook(String title, int sizeMb) {
super(title);
this.sizeMb = sizeMb;
}
int getSizeMb() {
return sizeMb;
}
@Override
String kind() {
return "ebook";
}
@Override
int loanDays() {
return 21;
}
}
class Dvd extends Item {
Dvd(String title) {
super(title);
}
@Override
String kind() {
return "dvd";
}
@Override
int loanDays() {
return 3;
}
}Longest: 21 Shortest: 3
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 21: רשימה אחת לכל הסוגיםShelf, step 21: one list for every kind
תזכורת: מה ביקשוReminder: the task
ב-List<Item> יש Emma (ספר), Dune (ebook), Alien (dvd) ו-Emma (ebook). הדפיסו שורה לכל פריט (Dune (ebook, 21 days)), וספרו כמה יש מכל סוג ב-TreeMap: {dvd=1, ebook=2, item=1}.
A List<Item> holds Emma (a book), Dune (ebook), Alien (dvd) and Emma (ebook). Print a line per item (Dune (ebook, 21 days)), and count each kind in a TreeMap: {dvd=1, ebook=2, item=1}.
סימולציה: הפתרון רץ שורה אחרי שורה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
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
List<Item> shelf = List.of(new Item("Emma"), new EBook("Dune", 2), new Dvd("Alien"), new EBook("Emma", 1));
Map<String, Integer> perKind = new TreeMap<>();
for (Item it : shelf) {
System.out.println(it.line());
perKind.put(it.kind(), perKind.getOrDefault(it.kind(), 0) + 1);
}
System.out.println(perKind);
}
}
class Item {
protected final String title;
Item(String title) {
this.title = title;
}
String kind() {
return "item";
}
int loanDays() {
return 14;
}
String line() {
return title + " (" + kind() + ", " + loanDays() + " days)";
}
}
class EBook extends Item {
private final int sizeMb;
EBook(String title, int sizeMb) {
super(title);
this.sizeMb = sizeMb;
}
int getSizeMb() {
return sizeMb;
}
@Override
String kind() {
return "ebook";
}
@Override
int loanDays() {
return 21;
}
}
class Dvd extends Item {
Dvd(String title) {
super(title);
}
@Override
String kind() {
return "dvd";
}
@Override
int loanDays() {
return 3;
}
}Emma (item, 14 days)
Dune (ebook, 21 days)
Alien (dvd, 3 days)
Emma (ebook, 21 days)
{dvd=1, ebook=2, item=1}יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מלכודת בבנאיA trap in the constructor
תזכורת: מה ביקשוReminder: the task
הבנאי של Parent קורא ל-name(), ו-Child דורסת את name() ומחזירה שדה. הריצו וצפו: הפלט הוא Hello, null ואז Now: Noa. כתבו את הקוד והבינו למה בסימולציה.
Parent's constructor calls name(), and Child overrides name() returning a field. Run it and watch: the output is Hello, null then Now: Noa. Write the code and understand why in the simulation.
סימולציה: הפתרון רץ שורה אחרי שורה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
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
public static void main(String[] args) {
new Child("Noa");
}
}
class Parent {
Parent() {
System.out.println("Hello, " + name());
}
String name() {
return "parent";
}
}
class Child extends Parent {
private final String name;
Child(String name) {
super();
this.name = name;
System.out.println("Now: " + name());
}
@Override
String name() {
return name;
}
}Hello, null Now: Noa
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
הצורה הגדולהThe largest shape
תזכורת: מה ביקשוReminder: the task
static Shape largest(Shape[] shapes) מחזירה את הצורה עם השטח הגדול. describe() ב-Shape משתמשת ב-getClass().getSimpleName(). עבור ריבוע 3, עיגול 2 וריבוע 1, הדפיסו Circle 12.57.
static Shape largest(Shape[] shapes) returns the shape with the largest area. describe() in Shape uses getClass().getSimpleName(). For a square of 3, a circle of 2 and a square of 1, print Circle 12.57.
סימולציה: הפתרון רץ שורה אחרי שורה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
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
static Shape largest(Shape[] shapes) {
Shape best = shapes[0];
for (Shape s : shapes) {
if (s.area() > best.area()) {
best = s;
}
}
return best;
}
public static void main(String[] args) {
Shape[] shapes = {new Square(3), new Circle(2), new Square(1)};
System.out.println(largest(shapes).describe());
}
}
abstract class Shape {
abstract double area();
String describe() {
return getClass().getSimpleName() + String.format(" %.2f", area());
}
}
class Square extends Shape {
private final double side;
Square(double side) {
this.side = side;
}
@Override
double area() {
return side * side;
}
}
class Circle extends Shape {
private final double r;
Circle(double r) {
this.r = r;
}
@Override
double area() {
return Math.PI * r * r;
}
}Circle 12.57
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.