JavaJava · Chapterبەش 8 · Lectureوانە 8.2
Method Overloading and Scopeفرەپێناسەکردنی میتۆد و مەودا
Overload methods in Java: one name with different parameter lists, the signature, how the compiler picks a version (exact types, widening, never narrowing; no match and ambiguous calls), println and Math.max as overloads, and why the return type does not count. Then scope: local variables, method and block scope, the same name in two places, shadowing a class variable, and pass by value.
لە Javaـدا: یەک ناو بە لیستی جیاواز، ، چۆن وەشانێک هەڵدەبژێرێت (جۆری ڕێک، فراوانکردن، هەرگیز تەسککردنەوە نا؛ بانگکردنی نەگونجاو و ناڕوون)، println و Math.max وەک نموونە و بۆچی ناژمێردرێت. پاشان : ، و بلۆک، هەمان ناو لە دوو شوێندا، و .
What you will learnچی فێر دەبیت
- Write overloaded methods and tell which signatures are allowed.
- Predict which overload runs, and fix no-match and ambiguous calls.
- Use local, method and block scope correctly and explain shadowing.
- Explain pass by value and return a new value instead of changing a parameter.
- فرەپێناسە بنووسیت و بزانیت کام ڕێگەپێدراون.
- پێشبینی بکەیت کام وەشان جێبەجێ دەبێت و بانگکردنی نەگونجاو و ناڕوون چاک بکەیت.
- ناوخۆیی، و بلۆک بە دروستی بەکار بهێنیت و ڕوون بکەیتەوە.
- ڕوون بکەیتەوە و لە جیاتی گۆڕینی نوێ بگەڕێنیتەوە.
One name, several methodsیەک ناو، چەند میتۆدێک
Adding two whole numbers and adding two decimals is the same job. Without a special rule you would need two names for it:
کۆکردنەوەی دوو و کۆکردنەوەی دوو هەمان کارن. بەبێ یاسایەکی تایبەت دوو ناوت بۆی پێویست دەبوو:
public class SeparateNames {
public static void main(String[] args) {
System.out.println(addInts(2, 3));
System.out.println(addDoubles(2.5, 3.25));
}
static int addInts(int a, int b) {
return a + b;
}
static double addDoubles(double a, double b) {
return a + b;
}
}$ java SeparateNames 5 5.75
Java lets several methods of a class share one name, as long as their parameter lists differ: in the number of parameters, their types, or the order of the types. This is . The caller then remembers one name, add, and Java picks the right version:
Java ڕێگە دەدات چەند یەک یەک ناویان هەبێت، بە مەرجێک لیستی جیاواز بێت: لە ژمارەی ، جۆرەکانیان یان ڕیزبەندیی جۆرەکان. ئەمە . ئیتر تەنیا یەک ناو لە بیر دەهێڵێتەوە (add) و Java وەشانە دروستەکە هەڵدەبژێرێت:
public class AddDemo {
public static void main(String[] args) {
System.out.println(add(2, 3));
System.out.println(add(2.5, 3.25));
System.out.println(add(1, 2, 3));
}
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
}$ java AddDemo 5 5.75 6
Writing several methods with the same name but different lists in one class, such as add(int, int) and add(double, double). Java picks the version whose parameters match the ; the alone cannot tell them apart. Compare .
نووسینی چەند بە هەمان ناو بەڵام بە لیستی جیاواز لە یەک ، وەک add(int, int) و add(double, double). Java ئەو وەشانە هەڵدەبژێرێت کە لەگەڵ دەگونجێن؛ تەنیا ناتوانێت لێکیان جیا بکاتەوە. بەراوردی بکە لەگەڵ .
An everyday picture: the word open. You open a door, a book or a bottle — one word, and what you hand it decides what happens. Overloading is the same: one method name, and the arguments decide which body runs.
وێنەیەکی ڕۆژانە: وشەی کردنەوە. دەرگا، کتێب یان بوتڵ دەکەیتەوە — یەک وشە و ئەوەی دەیدەیتێ بڕیار دەدات چی ڕوو دەدات. هەمان شتە: یەک ناوی و بڕیار دەدەن کام جێبەجێ دەبێت.
One name, several methodsیەک ناو، چەند میتۆدێک
The signatureواژووی کردار
Java tells methods apart by their : the name plus the types of the parameters, in order. static double add(double a, double b) has the signature add(double, double). The return type, the parameter names and modifiers such as static are not part of it. Two methods in one class may never have the same signature.
Java بە لێک جیا دەکاتەوە: ناو لەگەڵ جۆری ، بە ڕیزبەندی. static double add(double a, double b) add(double, double)ـە. ، ناوی و وشەی وەک static بەشێک نین لێی. دوو لە یەک هەرگیز نابێت هەمان هەبێت.
Because the order of the types counts, describe(String, int) and describe(int, String) are two different methods (legal, though easy to confuse):
چونکە ڕیزبەندیی جۆرەکان گرنگە، describe(String, int) و describe(int, String) دوو جیاوازن (یاسایین، بەڵام ئاسان تێکەڵ دەکرێن):
public class OrderOverload {
public static void main(String[] args) {
describe("Aram", 85);
describe(85, "Aram");
}
static void describe(String name, int mark) {
System.out.println("describe(String, int): " + name + " " + mark);
}
static void describe(int mark, String name) {
System.out.println("describe(int, String): " + mark + " " + name);
}
}$ java OrderOverload describe(String, int): Aram 85 describe(int, String): 85 Aram
How Java chooses a versionJava چۆن وەشانێک هەڵدەبژێرێت
The compiler decides, before the program runs, by looking at the types of the arguments. Each version below prints its own name, so the real run shows which one was chosen:
پێش جێبەجێبوونی بڕیار دەدات، بە سەیرکردنی جۆری . هەر وەشانێکی خوارەوە ناوی خۆی چاپ دەکات، بۆیە جێبەجێکردنی ڕاستەقینە پیشان دەدات کامیان هەڵبژێردرا:
public class WhichAdd {
public static void main(String[] args) {
System.out.println(add(2, 3));
System.out.println(add(2.5, 3));
System.out.println(add(1, 2, 3));
System.out.println(add('A', 1));
System.out.println(add(2L, 3));
}
static int add(int a, int b) {
System.out.print("[add(int, int)] ");
return a + b;
}
static double add(double a, double b) {
System.out.print("[add(double, double)] ");
return a + b;
}
static int add(int a, int b, int c) {
System.out.print("[add(int, int, int)] ");
return a + b + c;
}
}$ java WhichAdd [add(int, int)] 5 [add(double, double)] 5.5 [add(int, int, int)] 6 [add(int, int)] 66 [add(double, double)] 5.0


The rules, simply: a version fits if every argument has the parameter's type or can be widened to it without loss (char → int → long → float → double, as in Widening). From the versions that fit, Java takes the most specific one, the closest match, so an exact match always wins. Narrowing (double → int) is never done automatically. Only when no version fits does Java also try boxing an int into an Integer (Wrapper classes) and methods with ... parameters.
یاساکان بە سادەیی: وەشانێک دەگونجێت ئەگەر هەموو جۆری هەبێت یان بتوانرێت بەبێ لەدەستدان فراوان بکرێت بۆی (char → int → long → float → double، وەک لە فراوانکردنی جۆر). لەو وەشانانەی دەگونجێن، Java تایبەتترینیان هەڵدەبژێرێت، واتە نزیکترینیان، بۆیە گونجانی ڕێک هەمیشە دەباتەوە. (double → int) هەرگیز خۆکار ناکرێت. تەنیا کاتێک هیچ وەشانێک ناگونجێت، Java هەوڵی خستنە ناو سندووقی int بۆ Integer (کلاسە پێچەرەوەکان) و بە ...ـیش دەدات.
How Java chooses a versionJava چۆن وەشانێک هەڵدەبژێرێت
When no version fitsکاتێک هیچ وەشانێک ناگونجێت
If no version fits, javac stops and lists the versions it tried, each with the reason it failed:
ئەگەر هیچ وەشانێک نەگونجێت، javac دەوەستێت و ئەو وەشانانە دەژمێرێت کە تاقی کردوونەتەوە، هەریەکەیان لەگەڵ هۆی سەرنەکەوتنی:
public class NoMatch {
public static void main(String[] args) {
System.out.println(add("2", 3));
}
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
}$ javac NoMatch.java
NoMatch.java:3: error: no suitable method found for add(String,int)
System.out.println(add("2", 3));
^
method NoMatch.add(int,int) is not applicable
(argument mismatch; String cannot be converted to int)
method NoMatch.add(double,double) is not applicable
(argument mismatch; String cannot be converted to double)
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 errorNarrowing is never automatic either. With only square(int n), the call square(2.5) is refused, because 2.5 would lose its fraction (Narrowing: you must write the cast):
هەرگیز خۆکار نییە. کاتێک تەنیا square(int n) هەیە، بانگکردنی square(2.5) ڕەت دەکرێتەوە، چونکە 2.5 بەشە کەرتییەکەی لەدەست دەدات (تەسککردنەوەی جۆر: دەبێت گۆڕینەکە بنووسیت):
public class NoNarrowing {
public static void main(String[] args) {
System.out.println(square(2.5));
}
static int square(int n) {
return n * n;
}
}$ javac NoNarrowing.java
NoNarrowing.java:3: error: incompatible types: possible lossy conversion from double to int
System.out.println(square(2.5));
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 errorHow Java chooses a versionJava چۆن وەشانێک هەڵدەبژێرێت
Two versions fit equally wellدوو وەشان وەک یەک دەگونجێن
Sometimes two versions fit and neither is closer. Then the call is ambiguous and javac refuses to guess:
هەندێک جار دوو وەشان دەگونجێن و هیچیان نزیکتر نییە. ئەوکات بانگکردنەکە ناڕوونە و javac ڕازی نابێت مەزەندە بکات:
public class Ambiguous {
public static void main(String[] args) {
show(1, 2);
}
static void show(int a, double b) {
System.out.println("show(int, double)");
}
static void show(double a, int b) {
System.out.println("show(double, int)");
}
}$ javac Ambiguous.java
Ambiguous.java:3: error: reference to show is ambiguous
show(1, 2);
^
both method show(int,double) in Ambiguous and method show(double,int) in Ambiguous match
1 errorWrite the arguments so that only one version fits, and the error disappears:
بەو شێوەیە بنووسە کە تەنیا یەک وەشان بگونجێت و هەڵەکە نامێنێت:
public class AmbiguousFixed {
public static void main(String[] args) {
show(1, 2.0);
show(1.0, 2);
}
static void show(int a, double b) {
System.out.println("show(int, double)");
}
static void show(double a, int b) {
System.out.println("show(double, int)");
}
}$ java AmbiguousFixed show(int, double) show(double, int)
println is overloadedprintln فرەپێناسەکردنی میتۆدی تێدایە
You have used overloading since your first program. In the lab task that printed "Hello", "World!" with a comma (println takes one value), javac listed every version of println. Here is that message in full: ten versions, each for one type of argument (or none), and none takes two:
لە یەکەم بەکار دەهێنیت. لەو ئەرکەی تاقیگەدا کە "Hello", "World!"ـی بە کۆما چاپ دەکرد (println تەنیا یەک نرخ وەردەگرێت)، javac هەموو وەشانەکانی printlnـی ژمارد. ئەمە پەیامەکەیە بە تەواوی: دە وەشان، هەریەکەیان بۆ یەک جۆری (یان بێ ) و هیچیان دوو وەرناگرێت:
public class PrintTwo {
public static void main(String[] args) {
System.out.println("Hello", "World!");
}
}$ javac PrintTwo.java
PrintTwo.java:3: error: no suitable method found for println(String,String)
System.out.println("Hello", "World!");
^
method PrintStream.println() is not applicable
(actual and formal argument lists differ in length)
method PrintStream.println(boolean) is not applicable
(actual and formal argument lists differ in length)
method PrintStream.println(char) is not applicable
(actual and formal argument lists differ in length)
method PrintStream.println(int) is not applicable
(actual and formal argument lists differ in length)
method PrintStream.println(long) is not applicable
(actual and formal argument lists differ in length)
method PrintStream.println(float) is not applicable
(actual and formal argument lists differ in length)
method PrintStream.println(double) is not applicable
(actual and formal argument lists differ in length)
method PrintStream.println(char[]) is not applicable
(actual and formal argument lists differ in length)
method PrintStream.println(String) is not applicable
(actual and formal argument lists differ in length)
method PrintStream.println(Object) is not applicable
(actual and formal argument lists differ in length)
1 errorThe argument's type picks the version. 'A' is a char and prints as a letter, but 'A' + 1 is an int (A char is a number), and "A" + 1 is a String:
جۆری وەشانەکە هەڵدەبژێرێت. 'A' charـە و وەک پیت چاپ دەبێت، بەڵام 'A' + 1 intـە (char ژمارەیەکە) و "A" + 1 Stringـە:
public class PrintPick {
public static void main(String[] args) {
System.out.println('A');
System.out.println('A' + 1);
System.out.println((char) ('A' + 1));
System.out.println(65);
System.out.println(65.0);
System.out.println(1.5f);
System.out.println(true);
System.out.println("A" + 1);
}
}$ java PrintPick A 66 B 65 65.0 1.5 true A1
Math.max and Math.abs are overloaded the same way, for int, long, float and double (Math.max and Math.min): Math.max(3, 7) gives 7, Math.max(3, 7.0) gives 7.0 (real run).
Math.max و Math.abs بە هەمان شێوە هەیە، بۆ int، long، float و double (Math.max و Math.min): Math.max(3, 7) 7 دەدات و Math.max(3, 7.0) 7.0 (جێبەجێکردنی ڕاستەقینە).
The return type alone is not enoughتەنیا جۆری نرخی گەڕاوە بەس نییە
Two methods that differ only in their return type cannot live in one class. A call such as half(7); shows only the name and the argument types, so Java could not know which one you mean. javac refuses the second method:
دوو کە تەنیا لە جیاوازن ناتوانن لە یەک بژین. بانگکردنێکی وەک half(7); تەنیا ناو و جۆری پیشان دەدات، بۆیە Java ناتوانێت بزانێت مەبەستت کامیانە. javac دووەم ڕەت دەکاتەوە:
public class HalfDemo {
public static void main(String[] args) {
System.out.println(half(7));
}
static int half(int n) {
return n / 2;
}
static double half(int n) {
return n / 2.0;
}
}$ javac HalfDemo.java
HalfDemo.java:10: error: method half(int) is already defined in class HalfDemo
static double half(int n) {
^
1 errorParameter names do not count either: add(int a, int b) and add(int x, int y) have the same signature, add(int,int):
ناوی گرنگ نین: add(int a, int b) و add(int x, int y) هەمان هەیە، add(int,int):
public class NamesOnly {
public static void main(String[] args) {
System.out.println(add(2, 3));
}
static int add(int a, int b) {
return a + b;
}
static int add(int x, int y) {
return x + y;
}
}$ javac NamesOnly.java
NamesOnly.java:10: error: method add(int,int) is already defined in class NamesOnly
static int add(int x, int y) {
^
1 errorScope: where a variable can be usedمەودا: گۆڕاوێک لە کوێ بەکار دێت
Every variable can be used only in one part of the program: its . In Java the rule is simple: a variable is known from its declaration down to the closing brace } of the block it was declared in. Inner blocks can see the variables of the blocks around them; outer blocks cannot see inside.
هەموو تەنیا لە بەشێکی بەکار دێت: . لە Javaـدا یاساکە سادەیە: لە تا کەوانەی داخستنی }ـی ئەو بلۆکەی تێیدا ناسێنراوە دەناسرێت. بلۆکە ناوەکییەکان بلۆکەکانی دەوروبەریان دەبینن؛ بلۆکە دەرەکییەکان ناتوانن ناوەوە ببینن.
The part of a program where a name, such as a variable, can be used. A variable made inside a has ; one made outside all functions has .
ئەو بەشەی کە ناوێک، وەک ، تێیدا بەکار دێت. گۆڕاوێک کە لەناو دروست دەکرێت، تەنیا لەناو دەناسرێت؛ گۆڕاوێک کە لە دەرەوەی هەموو دروست دەکرێت، دەکەوێتە ناو .
An everyday picture: a school. A notice on the school board is for everyone (the class); the classroom board is only for that class (a method); a group's notebook only for the group (a block). Python works differently: it has no block scope (Where a variable lives, Variable scope).
وێنەیەکی ڕۆژانە: قوتابخانەیەک. ڕاگەیاندنێک لەسەر تەختەی قوتابخانە بۆ هەمووانە ()؛ تەختەی پۆلەکە تەنیا بۆ ئەو پۆلەیە ()؛ دەفتەری گرووپێک تەنیا بۆ گرووپەکە (بلۆکێک). Python جیاواز کار دەکات: نییە (گۆڕاوێک لە کوێ دەژی، مەودای گۆڕاوەکان).
Scope: where a variable can be usedمەودا: گۆڕاوێک لە کوێ بەکار دێت
Method scope: local variablesمەودای ناوخۆیی: گۆڕاوە ناوخۆییەکان
A variable declared in a method is a . Another method cannot see it, even when main calls that method:
کە لە ناسێنرابێت . تر ناتوانێت بیبینێت، تەنانەت کاتێک main بانگی ئەو دەکات:
public class ScopeDemo {
public static void main(String[] args) {
int total = 50;
printTotal();
}
static void printTotal() {
System.out.println(total);
}
}$ javac ScopeDemo.java
ScopeDemo.java:8: error: cannot find symbol
System.out.println(total);
^
symbol: variable total
location: class ScopeDemo
1 errorTo give a method a value, pass it as an argument. Parameters are local variables of their method too; each call creates them anew and they disappear when it returns. A local variable is also unknown on the lines before its declaration:
بۆ ئەوەی بدەیتە ، وەک بینێرە. ؛ هەر بانگکردنێک لە نوێوە دروستیان دەکات و کاتێک دەگەڕێتەوە نامێنن. لەو دێڕانەی پێش ناناسرێت:
public class ScopeFixed {
public static void main(String[] args) {
int total = 50;
printTotal(total);
}
static void printTotal(int total) {
System.out.println("total = " + total);
}
}$ java ScopeFixed total = 50
public class BeforeDeclaration {
public static void main(String[] args) {
System.out.println(x);
int x = 5;
}
}$ javac BeforeDeclaration.java
BeforeDeclaration.java:3: error: cannot find symbol
System.out.println(x);
^
symbol: variable x
location: class BeforeDeclaration
1 errorScope: where a variable can be usedمەودا: گۆڕاوێک لە کوێ بەکار دێت
Block scopeمەودای بلۆک
Every pair of braces makes a block, and a variable declared inside it ends at its closing brace: . Here message exists only in the if block:
هەموو جووتە کەوانەیەکی لوول بلۆکێک دروست دەکات و کە لە ناویدا بناسێنرێت لە کەوانەی داخستنیدا کۆتایی دێت: . لێرەدا message تەنیا لە بلۆکی ifـدا هەیە:
public class BlockScope {
public static void main(String[] args) {
int mark = 85;
if (mark >= 50) {
String message = "pass";
System.out.println(message);
}
System.out.println(message);
}
}$ javac BlockScope.java
BlockScope.java:8: error: cannot find symbol
System.out.println(message);
^
symbol: variable message
location: class BlockScope
1 errorpublic class BlockFixed {
public static void main(String[] args) {
int mark = 85;
String message;
if (mark >= 50) {
message = "pass";
} else {
message = "fail";
}
System.out.println(message);
}
}$ java BlockFixed pass
Loops follow the same rule: the variable of a for header lives only in that loop (The loop variable lives only in the loop). That is why two loops in one method may both use i: they are two different variables.
هەمان یاسا دەگرنە بەر: سەرەی for تەنیا لەو دەژی (گۆڕاوی خول تەنیا لە ناو خولەکەدا دەژی). بۆیە دوو لە یەک دەتوانن هەردووکیان i بەکار بهێنن: دوو جیاوازن.
public class LoopReuse {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
System.out.print(i + " ");
}
System.out.println();
for (int i = 10; i <= 30; i += 10) {
System.out.print(i + " ");
}
System.out.println();
}
}$ java LoopReuse 1 2 3 10 20 30
Scope: where a variable can be usedمەودا: گۆڕاوێک لە کوێ بەکار دێت
The same name in two placesهەمان ناو لە دوو شوێندا
Two methods may each have a variable called total. They are two separate variables that happen to share a name; changing one never touches the other:
دوو دەتوانن هەریەکەیان بە ناوی totalـیان هەبێت. دوو جیاوازن کە بە ڕێکەوت هەمان ناویان هەیە؛ گۆڕینی یەکێکیان هەرگیز دەست لە ئەوی تر نادات:
public class TwoTotals {
public static void main(String[] args) {
int total = 100;
addTen();
System.out.println("main's total: " + total);
}
static void addTen() {
int total = 10;
total = total + 10;
System.out.println("addTen's total: " + total);
}
}$ java TwoTotals addTen's total: 20 main's total: 100
Inside one method Java is stricter than many languages: a block may not declare a name that is already in use around it, and a local variable may not reuse a parameter's name (Java Language Specification §6.4). This stops a whole class of mix-ups:
لە ناو یەک Java لە زۆر زمان توندترە: بلۆکێک ناتوانێت ناوێک بناسێنێت کە لە دەوروبەریدا هێشتا بەکار دێت و ناتوانێت ناوی بەکار بهێنێتەوە (Java Language Specification §6.4). ئەمە ڕێگری لە کۆمەڵێک تێکەڵکردن دەکات:
public class AlreadyDefined {
public static void main(String[] args) {
int count = 5;
if (count > 0) {
int count = 10;
System.out.println(count);
}
}
static void show(int n) {
int n = 3;
System.out.println(n);
}
}$ javac AlreadyDefined.java
AlreadyDefined.java:5: error: variable count is already defined in method main(String[])
int count = 10;
^
AlreadyDefined.java:11: error: variable n is already defined in method show(int)
int n = 3;
^
2 errorsScope: where a variable can be usedمەودا: گۆڕاوێک لە کوێ بەکار دێت
Shadowing a class variableسێبەرخستنی گۆڕاوێکی کلاس
A variable can also be declared in the class itself, outside every method, with static: it belongs to the class, and all its methods can use it (static members). Java has no global variables; this is the nearest thing. If a method declares a local variable with the same name, the local one hides the class one from its declaration on. This is ; the class variable is still reachable with the class name:
دەتوانرێت لە خودی بناسێنرێت، لە دەرەوەی هەموو ، بە static: سەر بە و هەموو دەتوانێت بەکاری بهێنێت (ئەندامە ستاتیکەکان). Java هیچ نییە؛ ئەمە نزیکترین شتە. ئەگەر بە هەمان ناو بناسێنێت، ناوخۆییەکە لە ئەوەی دەشارێتەوە. ئەمە ؛ هێشتا بە ناوی دەگاتێ:
public class Shadow {
static int count = 100;
public static void main(String[] args) {
System.out.println("count = " + count);
int count = 5;
System.out.println("count = " + count);
System.out.println("Shadow.count = " + Shadow.count);
show();
}
static void show() {
System.out.println("in show: count = " + count);
}
}$ java Shadow count = 100 count = 5 Shadow.count = 100 in show: count = 100
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 5
Before the local declaration,
countstill means the class variable: 100.پێش ئەوەی بناسێنرێت،
countهێشتا واتای دەدات: 100.- Lineدێڕی 8
Shadow.countnames the class variable directly.Shadow.countڕاستەوخۆ ناوی دەبات.
Objects bring this back later: a parameter can hide a variable of the object (a field), and this.name still reaches it (this: the current object).
دواتر ئەمە دەهێننەوە: دەتوانێت بشارێتەوە و this.name هێشتا دەیگاتێ (this: ئۆبجێکتە ئێستاکە).
Java passes a copy of the valueJava کۆپییەکی نرخەکە دەنێرێت
When you call a method with a variable as the argument, the method gets a copy of its value, never the variable itself: . Changing the parameter changes only the copy:
کاتێک بانگ دەکەیت و وەک دەدەیت، کۆپییەکی وەردەگرێت، هەرگیز خودی نا: . گۆڕینی تەنیا کۆپییەکە دەگۆڕێت:
public class PassByValue {
public static void main(String[] args) {
int x = 5;
System.out.println("before: x = " + x);
addTen(x);
System.out.println("after: x = " + x);
}
static void addTen(int n) {
n = n + 10;
System.out.println("inside: n = " + n);
}
}$ java PassByValue before: x = 5 inside: n = 15 after: x = 5
The names do not matter: even if the parameter is also called x, it is a different variable (real run: inside: x = 15, after: x = 5). To change the caller's variable, return the new value and assign it:
ناوەکان گرنگ نین: تەنانەت ئەگەر ناوی x بێت، ترە (جێبەجێکردنی ڕاستەقینە: inside: x = 15، after: x = 5). بۆ گۆڕینی ، بگەڕێنەوە و دایبنێ:
public class ReturnNew {
public static void main(String[] args) {
int x = 5;
x = addTen(x);
System.out.println("after: x = " + x);
}
static int addTen(int n) {
return n + 10;
}
}$ java ReturnNew after: x = 15
Common mistakesهەڵە باوەکان
| You wroteنووسیت | What happensچی ڕوو دەدات | Fixچارەسەر |
|---|---|---|
int half(int n) + double half(int n) | method half(int) is already defined | Overload by parameters, or use two names.بە جیاوازیان بکە، یان دوو ناو بەکار بهێنە. |
area(double side) + area(double radius) | method area(double) is already defined | Names do not count: squareArea, circleArea.ناوەکان ناژمێردرێن: squareArea، circleArea. |
show(1, 2) | reference to show is ambiguous | Write show(1, 2.0) so that one version fits.show(1, 2.0) بنووسە تا یەک وەشان بگونجێت. |
square(2.5) | possible lossy conversion from double to int | Cast on purpose, or add a double version.بە ئەنقەست بیگۆڕە، یان وەشانێکی double زیاد بکە. |
| a variable used after its block دوای بلۆکەکەی بەکار هاتووە | cannot find symbol | Declare it before the block.پێش بلۆکەکە بیناسێنە. |
| main's variable used in another method main لە تردا | cannot find symbol | Pass it as an argument.وەک بینێرە. |
| the same name in an inner blockهەمان ناو لە بلۆکێکی ناوەوەدا | variable count is already defined | Choose another name.ناوێکی تر هەڵبژێرە. |
int calls = 0; | in a method: hides the class variableلە : دەشارێتەوە | Use the class variable; declare no local copy. بەکار بهێنە؛ هیچ کۆپییەکی ناوخۆیی مەناسێنە. |
changing an int parameterگۆڕینی int | the caller sees no change هیچ گۆڕانێک نابینێت | Return the new value: x = addTen(x);. بگەڕێنەوە: x = addTen(x);. |
Practiceڕاهێنان
You want area(double side) for a square and area(double radius) for a circle. Why does javac refuse it? Fix the design, and add area(double width, double height) for a rectangle.
دەتەوێت area(double side) بۆ چوارگۆشە و area(double radius) بۆ بازنە هەبێت. بۆچی javac ڕەتی دەکاتەوە؟ دیزاینەکە چاک بکە و area(double width, double height) بۆ لاکێشە زیاد بکە.
Show answerوەڵامەکە پیشان بدە
public class AreaClash {
public static void main(String[] args) {
System.out.println(area(3.0));
}
static double area(double side) {
return side * side;
}
static double area(double radius) {
return Math.PI * radius * radius;
}
}$ javac AreaClash.java
AreaClash.java:10: error: method area(double) is already defined in class AreaClash
static double area(double radius) {
^
1 errorBoth have the signature area(double). A different parameter name does not help, so the circle needs another method name; the rectangle's two parameters make a real overload:
هەردووکیان area(double)ـیان هەیە. ناوی جیاوازی یارمەتی نادات، بۆیە بازنەکە پێویستی بە ناوێکی تری هەیە؛ دوو لاکێشەکە بە ڕاستی دروست دەکەن:
public class Areas {
public static void main(String[] args) {
System.out.println(area(3.0));
System.out.println(area(4.0, 2.5));
System.out.printf("%.2f%n", circleArea(1.0));
}
static double area(double side) {
return side * side;
}
static double area(double width, double height) {
return width * height;
}
static double circleArea(double radius) {
return Math.PI * radius * radius;
}
}$ java Areas 9.0 10.0 3.14
Write max(int, int), max(int, int, int) (using the first) and max(double, double).
max(int, int)، max(int, int, int) (بە بەکارهێنانی یەکەمیان) و max(double, double) بنووسە.
Show answerوەڵامەکە پیشان بدە
public class MaxOverloads {
public static void main(String[] args) {
System.out.println(max(4, 9));
System.out.println(max(4, 9, 7));
System.out.println(max(2.5, 1.5));
}
static int max(int a, int b) {
return a > b ? a : b;
}
static int max(int a, int b, int c) {
return max(max(a, b), c);
}
static double max(double a, double b) {
return a > b ? a : b;
}
}$ java MaxOverloads 9 9 2.5
With print(int), print(double) and print(String), what does each call print? print(5), print(5.0), print("5"), print('5'), print(5L), print(5.0f).
بە print(int)، print(double) و print(String)، هەر بانگکردنێک چی چاپ دەکات؟ print(5)، print(5.0)، print("5")، print('5')، print(5L)، print(5.0f).
Show answerوەڵامەکە پیشان بدە
public class Predict {
public static void main(String[] args) {
print(5);
print(5.0);
print("5");
print('5');
print(5L);
print(5.0f);
}
static void print(int x) {
System.out.println("int: " + x);
}
static void print(double x) {
System.out.println("double: " + x);
}
static void print(String x) {
System.out.println("String: " + x);
}
}$ java Predict int: 5 double: 5.0 String: 5 int: 53 double: 5.0 double: 5.0
'5' is a char whose code is 53, widened to int. 5L (long) and 5.0f (float) have no exact version, and both widen to double.
'5' charـێکە کە کۆدەکەی 53ـە و فراوان دەبێت بۆ int. 5L (long) و 5.0f (float) وەشانی ڕێکیان نییە و هەردووکیان فراوان دەبن بۆ double.
This program has two scope errors. Name them before you compile.
ئەم دوو هەڵەی تێدایە. پێش کۆمپایلکردن ناویان ببە.
public class ScopeErrors {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
int square = i * i;
}
System.out.println(square);
report();
}
static void report() {
System.out.println(i);
}
}$ javac ScopeErrors.java
ScopeErrors.java:6: error: cannot find symbol
System.out.println(square);
^
symbol: variable square
location: class ScopeErrors
ScopeErrors.java:11: error: cannot find symbol
System.out.println(i);
^
symbol: variable i
location: class ScopeErrors
2 errorsShow answerوەڵامەکە پیشان بدە
square lives only inside the loop body, and i only inside the loop, which is in main; report can see neither. Declare what you need outside the loop and pass it as an argument.
square تەنیا لە ناو دەژی و i تەنیا لە ناو ، کە لە mainـدایە؛ report هیچیان نابینێت. ئەوەی پێویستتە لە دەرەوەی بیناسێنە و وەک بینێرە.
Why does this swap method print the swapped values but leave first and second unchanged?
بۆچی ئەم swapـە چاپ دەکات، بەڵام first و second ناگۆڕێت؟
public class SwapTry {
public static void main(String[] args) {
int first = 1;
int second = 2;
swap(first, second);
System.out.println("in main: first = " + first + ", second = " + second);
}
static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
System.out.println("in swap: a = " + a + ", b = " + b);
}
}$ java SwapTry in swap: a = 2, b = 1 in main: first = 1, second = 2
Show answerوەڵامەکە پیشان بدە
a and b are copies of 1 and 2 (pass by value). The method swaps its copies, which disappear when it returns. A method returns one value, so swap two variables where they live, in main, with a temporary variable (Tracing: swapping two values).
a و b کۆپیی 1 و 2ـن (ناردن بە نرخ). کۆپییەکانی خۆی ئاڵوگۆڕ دەکات، کە کاتی گەڕانەوە نامێنن. یەک دەگەڕێنێتەوە، بۆیە دوو لەو شوێنەی تێیدا دەژین ئاڵوگۆڕ بکە، لە main، بە کاتی (بەدواداچوون: ئاڵوگۆڕی دوو نرخ).
Write doubleIt(int value) that changes its parameter and a doubled(int value) that returns value * 2. Call both on price = 750 and print price after each.
doubleIt(int value) بنووسە کە دەگۆڕێت و doubled(int value) کە value * 2 دەگەڕێنێتەوە. هەردووکیان لەسەر price = 750 بانگ بکە و دوای هەریەکەیان price چاپ بکە.
Show answerوەڵامەکە پیشان بدە
public class DoubleIt {
public static void main(String[] args) {
int price = 750;
doubleIt(price);
System.out.println("after doubleIt: " + price);
price = doubled(price);
System.out.println("after doubled: " + price);
}
static void doubleIt(int value) {
value = value * 2;
}
static int doubled(int value) {
return value * 2;
}
}$ java DoubleIt after doubleIt: 750 after doubled: 1500
Summaryکورتە
- Overloading: several methods with one name and different parameter lists (number, types or order of types).
- The signature is the name plus the parameter types; the return type and parameter names do not count.
- javac picks the most specific version that fits, with exact types or widening; never narrowing. No fit or two equal fits stop the compiler.
- Scope: a variable is known from its declaration to the closing brace of its block. Locals of one method are invisible to others.
- A local variable with the name of a class variable shadows it; the class variable is still
ClassName.name. - Java passes copies of values: changing a parameter never changes the caller's variable; return the new value instead.
- : چەند بە یەک ناو و لیستی جیاواز (ژمارە، جۆر یان ڕیزبەندیی جۆرەکان).
- ناو لەگەڵ جۆری ؛ و ناوی ناژمێردرێن.
- javac تایبەتترین وەشان هەڵدەبژێرێت کە دەگونجێت، بە جۆری ڕێک یان فراوانکردن؛ هەرگیز تەسککردنەوە نا. نەگونجان یان دوو گونجانی یەکسان دەوەستێنن.
- : لە تا کەوانەی داخستنی بلۆکەکەی دەناسرێت. ناوخۆییەکانی بۆ ئەوانی تر نابینرێن.
- بە ناوی ئەو دەشارێتەوە ()؛ هێشتا
ClassName.nameـە. - Java کۆپیی دەنێرێت: گۆڕینی هەرگیز ناگۆڕێت؛ لە جیاتی ئەوە بگەڕێنەوە.
Why can't two methods differ only in their return type?بۆچی دوو میتۆد ناتوانن تەنیا لە جۆری نرخی گەڕاوەدا جیاواز بن؟
A call shows only the name and the argument types, so Java could not choose between them; javac says already defined.
بانگکردنێک تەنیا ناو و جۆری پیشان دەدات، بۆیە Java ناتوانێت لە نێوانیاندا هەڵبژێرێت؛ javac دەڵێت already defined.
What does cannot find symbol usually mean for a variable?cannot find symbol بۆ گۆڕاوێک زۆرجار چی دەگەیەنێت؟
The variable is used outside its scope: after its block ended, before its declaration, or in another method.
لە دەرەوەی بەکار هاتووە: دوای کۆتایی بلۆکەکەی، پێش ، یان لە تردا.
How can a method give a new value back to its caller?میتۆدێک چۆن دەتوانێت نرخێکی نوێ بداتەوە بە بانگکەرەکەی؟
By returning it: x = addTen(x);. Changing the parameter changes only the method's copy.
بە گەڕاندنەوەی: x = addTen(x);. گۆڕینی تەنیا کۆپییەکەی دەگۆڕێت.
Lesson complete!وانەکە تەواو بوو!
Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.
Key termsزاراوە سەرەکییەکان
Recursionخۆبانگکردنەوە
Related lecturesوانە پەیوەندیدارەکان
- Recursionخۆبانگکردنەوە
- Type Casting: Widening and Narrowingگۆڕینی جۆر: فراوانکردنی جۆر و تەسککردنەوەی جۆر
- The for Loop and Nested Loopsخولی for و خولە ناوەکییەکان
- The Math Classکلاسەکەی Math
- Your First Java Program: Output and Commentsیەکەم بەرنامەی Javaـت: دەرخستە و لێدوانەکان
- Variable Scope: Local and Globalمەودای گۆڕاوەکان: ناوخۆیی و گشتی
- Positional, Keyword and Default Argumentsئارگیومێنتە شوێنییەکان، ئارگیومێنتە ناودارەکان و نرخە بنەڕەتییەکان
- Python Next to JavaPython لە تەنیشت Javaـەوە
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
- W3Schools: Java Method Overloading
- W3Schools: Java Scope
- The Java Tutorials: Defining Methods (overloading, signature)
- The Java Tutorials: Passing Information to a Method or a Constructor (pass by value, shadowing)
- Java Language Specification (Java SE 17), §8.4.2 Method Signature and §8.4.9 Overloading
- Java Language Specification (Java SE 17), §15.12.2 Compile-Time Step 2: Determine Method Signature
- Java Language Specification (Java SE 17), §6.3 Scope of a Declaration and §6.4 Shadowing
- Sedgewick and Wayne, Introduction to Programming in Java, 2.1 Static Methods
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.