התעלמות נגד העמסה ב-Java

הקדמה

החלפת הגדרות ו־עומס הם מושגים מרכזיים בתכנות בִּשפת ג'אווה. אלו הם הדרכים ליישום הפולימורפיזם בתכניות ה־Java שלנו. פולימורפיזם הוא אחד ממושגי ה־עקרונות OOPS.

Screenshot of Java code with arrows pointing at instances where overloading and overriding are occurring.

כאשר חתימת השיטה (שם ופרמטרים) זהה בכיתת האב ובכיתת הילד, נקרא זה החלפה. כאשר שתי או יותר מתודות באותה המחלקה יש להם את אותו השם אך פרמטרים שונים, נקרא זה עומס.

השוואה בין החלפה ועומס

Overriding Overloading
Implements “runtime polymorphism” Implements “compile time polymorphism”
The method call is determined at runtime based on the object type The method call is determined at compile time
Occurs between superclass and subclass Occurs between the methods in the same class
Have the same signature (name and method arguments) Have the same name, but the parameters are different
On error, the effect will be visible at runtime On error, it can be caught at compile time

דוגמה על החלפה ועומס

כאן דוגמה לעומס ולהחלפה בתכנית Java:

package com.journaldev.examples;

import java.util.Arrays;

public class Processor {

	public void process(int i, int j) {
		System.out.printf("Processing two integers:%d, %d", i, j);
	}

	public void process(int[] ints) {
		System.out.println("Adding integer array:" + Arrays.toString(ints));
	}

	public void process(Object[] objs) {
		System.out.println("Adding integer array:" + Arrays.toString(objs));
	}
}

class MathProcessor extends Processor {

	@Override
	public void process(int i, int j) {
		System.out.println("Sum of integers is " + (i + j));
	}

	@Override
	public void process(int[] ints) {
		int sum = 0;
		for (int i : ints) {
			sum += i;
		}
		System.out.println("Sum of integer array elements is " + sum);
	}

}

החלפה

השיטה process() והפרמטרים int i, int j במחלקה Processor מופרטים מחדש במחלקה היורשת MathProcessor. שורה 7 ושורה 23:

public class Processor {

    public void process(int i, int j) { /* ... */ }

}

/* ... */

class MathProcessor extends Processor {
 
    @Override
    public void process(int i, int j) {  /* ... */ }

}

והשיטה process() והפרמטר int[] ints במחלקה Processor מופרטים גם במחלקה היורשת. שורה 11 ושורה 28:

public class Processor {

    public void process(int[] ints) { /* ... */ }

}

/* ... */

class MathProcessor extends Processor {

    @Override
    public void process(Object[] objs) { /* ... */ }

}

עמידה במשקל

השיטה process() מופרטת במחלקה Processor. שורות 7, 11 ו-15:

public class Processor {

    public void process(int i, int j) { /* ... */ }

    public void process(int[] ints) { /* ... */ }

    public void process(Object[] objs) { /* ... */ }

}

סיכום

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

Source:
https://www.digitalocean.com/community/tutorials/overriding-vs-overloading-in-java