JavaJava · Chapterبەش 10 · Lectureوانە 10.2

Constructors, Modifiers and Encapsulationدروستکەرەکان، دیاریکەرەکان و کەپسوولکردن

Constructors set up every new object: the class's name and no return type, the default constructor that javac adds and that disappears once you write your own, parameters and this, overloaded constructors and this(...) chaining. Then who may use what: public, private, protected and package access, the non-access modifiers static, final and abstract, a static counter of created objects, final fields, and encapsulation with private fields and getters and setters that check every value, such as a mark from 0 to 100. Records (Java 16+) appear as an extra.

هەموو نوێ ئامادە دەکەن: ناوی و بێ ، بنەڕەتی کە javac زیادی دەکات و کاتێک هی خۆت دەنووسیت نامێنێت، و this، بۆ و زنجیرەی this(...). پاشان کێ دەتوانێت چی بەکار بهێنێت: public، private، protected و دەستڕاگەیشتنی ، دیاریکەرەکانی static، final و abstract، static بۆ دروستکراو، final و بە private و و کە هەموو دەپشکنن، وەک نمرەیەک لە 0 تا ⁦100. record (Java 16+)⁩ وەک زیادە دێت.

22 min read20 خولەک خوێندنەوە · 22 stepsهەنگاو

What you will learnچی فێر دەبیت

  • Write constructors with parameters, use this, overload constructors and chain them with this(...).
  • Explain the default constructor and fix 'constructor … cannot be applied to given types'.
  • Choose public, private, protected or package access, and use static and final fields correctly.
  • Encapsulate a class with private fields and getters and setters that validate values.
  • بە بنووسیت، this بەکار بهێنیت، فرەپێناسە بکەیت و بە this(...) بیانبەستیتەوە بە یەکەوە.
  • بنەڕەتی ڕوون بکەیتەوە و هەڵەی constructor … cannot be applied to given types چاک بکەیت.
  • public، private، protected یان دەستڕاگەیشتنی هەڵبژێریت و static و final بە دروستی بەکار بهێنیت.
  • بە private و و پشکنەر کەپسوول بکەیت.

Why constructors?بۆچی دروستکەرەکان؟

In the last lesson every object took several lines: new Student(), then one line for each field. Forget one line and the field quietly keeps its default value; nothing warns you:

لە وانەی پێشوودا هەر چەند دێڕێکی دەویست: new Student()، پاشان بۆ هەر دێڕێک. دێڕێک لەبیر بکە و بە بێدەنگی دەهێڵێتەوە؛ هیچ شتێک ئاگادارت ناکاتەوە:

ForgotMark.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Student {
    String name;
    int mark;

    void printReport() {
        System.out.println(name + " has " + mark + " marks.");
    }
}

public class ForgotMark {
    public static void main(String[] args) {
        Student aram = new Student();
        aram.name = "Aram";
        aram.mark = 85;

        Student karwan = new Student();
        karwan.name = "Karwan";
        // the line karwan.mark = 47; was forgotten

        aram.printReport();
        karwan.printReport();
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 18

The line that should set Karwan's mark is missing.

ئەو دێڕەی دەبوو نمرەی Karwan دابنێت ون بووە.

A is special code in the class that runs every time new makes an object. It takes the values as parameters and fills the fields, so every new object is complete from its first moment.

کۆدێکی تایبەتە لە ناو کە هەر جارێک new دروست بکات جێبەجێ دەبێت. وەک وەردەگرێت و پڕ دەکاتەوە، بۆیە هەموو نوێ لە یەکەم ساتەوە تەواوە.

Left, without a constructor: Student karwan = new Student(); karwan.name = "Karwan"; and the comment // forgot: karwan.mark = 47; — the object has name "Karwan" and mark 0, and the program prints Karwan has 0 marks. (crossed). Right, with a constructor: Student karwan = new Student("Karwan", 47); — the object has name "Karwan" and mark 47, and the program prints Karwan has 47 marks. (ticked).لای چەپ، بەبێ دروستکەر: Student karwan = new Student(); karwan.name = "Karwan"; و لێدوانی // forgot: karwan.mark = 47; — ئۆبجێکتەکە name "Karwan" و mark 0ـی هەیە و بەرنامەکە Karwan has 0 marks. چاپ دەکات (✗). لای ڕاست، بە دروستکەر: Student karwan = new Student("Karwan", 47); — ئۆبجێکتەکە name "Karwan" و mark 47ـی هەیە و بەرنامەکە Karwan has 47 marks. چاپ دەکات (✓).
A constructor makes and fills an object in one step بە یەک هەنگاو دروست دەکات و پڕی دەکاتەوەCêIT

Writing a constructorنووسینی دروستکەرێک

A constructor looks like a method, with two differences: its name is exactly the class name, and it has no return type, not even void. Its parameters receive the arguments that you write after new:

لە دەچێت، بە دوو جیاوازی: ناوەکەی ڕێک ناوی و هیچ نییە، تەنانەت voidـیش. ئەو وەردەگرن کە دوای new دەیاننووسیت:

FirstConstructor.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Student {
    String name;
    int mark;

    Student(String studentName, int studentMark) {
        name = studentName;
        mark = studentMark;
        System.out.println("New student: " + name);
    }

    void printReport() {
        System.out.println(name + " has " + mark + " marks.");
    }
}

public class FirstConstructor {
    public static void main(String[] args) {
        Student aram = new Student("Aram", 85);
        Student shilan = new Student("Shilan", 92);
        aram.printReport();
        shilan.printReport();
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 5-9

The constructor: the class name, two parameters, no return type.

: ناوی ، دوو ، بێ .

Lineدێڕی 18-19

Each new runs the constructor once, with its own arguments.

هەر newـێک یەک جار جێبەجێ دەکات، بە خۆی.

Animation of Student aram = new Student("Aram", 85);. 1: the call is highlighted. 2: Java makes the object first; its fields start at name null and mark 0. 3: the arguments "Aram" and 85 go into the parameters studentName and studentMark. 4: name = studentName; fills the first field with "Aram". 5: mark = studentMark; fills the second field with 85. 6: the constructor ends, its parameters are gone, and aram refers to the filled object.
Animation of Student aram = new Student("Aram", 85);. 1: the call is highlighted. 2: Java makes the object first; its fields start at name null and mark 0. 3: the arguments "Aram" and 85 go into the parameters studentName and studentMark. 4: name = studentName; fills the first field with "Aram". 5: mark = studentMark; fills the second field with 85. 6: the constructor ends, its parameters are gone, and aram refers to the filled object.
The constructor fills the new object پڕ دەکاتەوەCêIT

Writing a constructorنووسینی دروستکەرێک

No return type, not even voidهیچ جۆرێکی نرخی گەڕاوە نییە، تەنانەت void

Write void before the constructor and javac does not complain about that line. It is now an ordinary method that happens to be called Student, and the class has no constructor of its own. The call with two arguments fails:

void پێش بنووسە و javac گلەیی لەو دێڕە ناکات. ئێستا ئاساییە کە بە ڕێکەوت ناوی Studentـە و هیچ خۆی نییە. بانگکردنەکە بە دوو سەرناکەوێت:

VoidConstructor.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Student {
    String name;
    int mark;

    void Student(String studentName, int studentMark) {
        name = studentName;
        mark = studentMark;
    }
}

public class VoidConstructor {
    public static void main(String[] args) {
        Student aram = new Student("Aram", 85);
        System.out.println(aram.name);
    }
}

The proof that it became a method: new Student() still works (javac added an empty constructor), and aram.Student("Aram", 85) is an ordinary method call. Even javac -Xlint:all prints no warning:

بەڵگەی ئەوەی بووە بە : new Student() هێشتا کار دەکات (javac بەتاڵی زیاد کرد) و aram.Student("Aram", 85) بانگکردنێکی ئاسایی . تەنانەت javac -Xlint:allـیش هیچ ئاگادارکردنەوەیەک چاپ ناکات:

VoidMethod.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Student {
    String name;
    int mark;

    void Student(String studentName, int studentMark) {
        name = studentName;
        mark = studentMark;
    }
}

public class VoidMethod {
    public static void main(String[] args) {
        Student aram = new Student();
        System.out.println(aram.name + " " + aram.mark);
        aram.Student("Aram", 85);
        System.out.println(aram.name + " " + aram.mark);
    }
}
Two cards. A constructor: Student(String n, int m) { name = n; mark = m; } — the class name with nothing before it; new Student("Aram", 85) runs the constructor (ticked). A method called Student: void Student(String n, int m) { … } — a return type makes it a method; new Student("Aram", 85) gives cannot be applied to given types, because only the hidden Student() exists (crossed). Note: javac does not warn you.دوو کارت. دروستکەرێک: Student(String n, int m) { name = n; mark = m; } — ناوی کلاسەکە، هیچ شتێک لە پێشیدا نییە؛ new Student("Aram", 85) دروستکەرەکە جێبەجێ دەکات (✓). میتۆدێک بە ناوی Student: void Student(String n, int m) { … } — جۆری نرخی گەڕاوە دەیکات بە میتۆد؛ new Student("Aram", 85) cannot be applied to given types دەدات، چونکە تەنیا Student()ـی شاراوە هەیە (✗). تێبینی: javac ئاگادارت ناکاتەوە.
A constructor has no return type, not even void نییە، تەنانەت voidـیشی نییەCêIT

The default constructorدروستکەری بنەڕەتی

Every class has at least one constructor. If you write none, javac adds a default constructor with no parameters and an empty body; that is why new Student() worked in the last lesson. javap, the JDK's class-file viewer (Inside a class file), shows it:

هەموو لانیکەم یەک هەیە. ئەگەر هیچ نەنووسیت، javac بنەڕەتی زیاد دەکات، بێ و بە جەستەیەکی بەتاڵ؛ هەر بۆیە new Student() لە وانەی پێشوودا کاری کرد. javap، پیشاندەری classـی JDK (ناوەوەی فایلێکی class)، پیشانی دەدات:

BASHType in a terminalلە تێرمیناڵدا بینووسە
javac Student.java
javap Student

The default constructor gets the class's access: for public class Student, javap shows public Student();. Before its own (empty) body it calls the constructor of the parent class with a hidden super(): see No super(...)? javac adds super().

بنەڕەتی هەمان دەستڕاگەیشتنی وەردەگرێت: بۆ public class Student، javap public Student(); پیشان دەدات. پێش جەستە (بەتاڵەکەی) خۆی، بە super()ـێکی شاراوە بانگی دەکات: ⁦super(...)⁩ نییە؟ javac خۆی ⁦super()⁩ زیاد دەکات ببینە.

What you write: class Student { String name; int mark; }. An arrow labelled javac leads to what javac makes (javap shows it): the same class with one more line, Student() { }, highlighted as the default constructor. Notes: it has no parameters and no code, so new Student() works; it gets the same access as the class, so public class gives public Student().ئەوەی تۆ دەینووسیت: class Student { String name; int mark; }. تیرێک بە ناوی javac دەچێت بۆ ئەوەی javac دروستی دەکات (javap پیشانی دەدات): هەمان کلاس بە دێڕێکی زیاترەوە، Student() { }، کە وەک دروستکەری بنەڕەتی دیار کراوە. تێبینییەکان: هیچ پارامیتەر و هیچ کۆدێکی نییە، بۆیە new Student() کار دەکات؛ هەمان دەستڕاگەیشتنی کلاسەکە وەردەگرێت، بۆیە public class دەبێتە public Student().
No constructor written? javac adds an empty oneهیچ نەنووسراوە؟ javac یەکێکی بەتاڵ زیاد دەکاتCêIT

The default constructorدروستکەری بنەڕەتی

Write one, and the default constructor is not addedیەکێک بنووسە، ئیتر دروستکەرە بنەڕەتییەکە زیاد ناکرێت

javac adds the default constructor only when the class has no constructor at all. As soon as you write Student(String, int), new Student() no longer compiles:

javac تەنیا کاتێک زیاد دەکات کە هیچ نەبێت. هەر کە Student(String, int) دەنووسیت، new Student() ئیتر کۆمپایل نابێت:

DefaultGone.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Student {
    String name;
    int mark;

    Student(String studentName, int studentMark) {
        name = studentName;
        mark = studentMark;
    }
}

public class DefaultGone {
    public static void main(String[] args) {
        Student aram = new Student("Aram", 85);
        Student nobody = new Student();
    }
}

The message lists what the class offers (required: String,int) and what you gave (found: no arguments). Either pass the arguments, or write a no-argument constructor yourself, as the next screen shows.

پەیامەکە ئەوەی پێشکەشی دەکات (required: String,int) و ئەوەی تۆ داوتە (found: no arguments) دەنووسێت. یان بنێرە، یان بێ خۆت بنووسە، وەک شاشەی داهاتوو پیشانی دەدات.

Two rows. No constructor written: class Student { … } — javac adds Student(), so new Student() works (ticked). You wrote Student(String, int): Student(String n, int m) { … } — javac adds nothing; new Student("Aram", 85) works (ticked) but new Student() fails with cannot be applied … (crossed). Note: need both? Write the no-argument constructor yourself as well.دوو ڕیز. هیچ دروستکەرێک نەنووسراوە: class Student { … } — javac Student() زیاد دەکات، بۆیە new Student() کار دەکات (✓). تۆ دروستکەری Student(String, int) دەنووسیت: Student(String n, int m) { … } — javac هیچ زیاد ناکات؛ new Student("Aram", 85) کار دەکات (✓) بەڵام new Student() بە cannot be applied … سەرناکەوێت (✗). تێبینی: هەردووکیانت دەوێت؟ Student()ـیش خۆت بنووسە.
Write a constructor, and the default one is not added بنووسە، ئیتر زیاد ناکرێتCêIT

this: the current objectthis: ئۆبجێکتە ئێستاکە

Names like studentName are clumsy, so programmers give a parameter the same name as its field. Inside the constructor, name then means the parameter, which shadows the field (Shadowing a class variable). The keyword this is a reference to the current object (the one being built, or the one a method was called on), so this.name is the field:

ناوی وەک studentName درێژ و ناڕێکن، بۆیە هەمان ناوی دەدەنە . ئەوکات لە ناو ، name واتە کە دەشارێتەوە (، سێبەرخستن). this بۆ ئێستاکە (ئەوەی دروست دەکرێت، یان ئەوەی لەسەر بانگ کراوە)، بۆیە this.name :

ThisDemo.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Student {
    String name;
    int mark;

    Student(String name, int mark) {
        this.name = name;
        this.mark = mark;
    }

    void printReport() {
        System.out.println(this.name + " has " + this.mark + " marks.");
    }
}

public class ThisDemo {
    public static void main(String[] args) {
        Student rebin = new Student("Rebin", 78);
        Student lana = new Student("Lana", 91);
        rebin.printReport();
        lana.printReport();
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 6-7

Left: the field of this object. Right: the parameter.

چەپ: ئەم . ڕاست: .

Lineدێڕی 11

In a method no parameter hides the fields, so this.name and name are the same field here.

لە هیچ ناشارێتەوە، بۆیە لێرەدا this.name و name هەمان .

The constructor Student(String name, int mark) { this.name = name; this.mark = mark; } with this.name and this.mark in blue (fields) and name and mark in green (parameters). Below, the constructor's parameters name = "Rebin" and mark = 78, with arrows to the fields of the object being built (name "Rebin", mark 78). A box this points to the same object: this = the object itself. Note: this.name = name; copies the parameter into the field.دروستکەری Student(String name, int mark) { this.name = name; this.mark = mark; } کە this.name و this.mark بە شین (تایبەتمەندییەکان) و name و mark بە سەوز (پارامیتەرەکان) دیار کراون. لە خوارەوە پارامیتەرەکانی دروستکەرەکە، name = "Rebin" و mark = 78، بە تیر بۆ تایبەتمەندییەکانی ئەو ئۆبجێکتەی دروست دەکرێت (name "Rebin"، mark 78). سندووقی this ئاماژە بۆ هەمان ئۆبجێکت دەکات: this = خودی ئۆبجێکتەکە. تێبینی: this.name = name; پارامیتەرەکە کۆپی دەکات بۆ ناو تایبەتمەندییەکە.
this.name is the field; name is the parameter⁦this.name⁩ ؛ name CêIT

this: the current objectthis: ئۆبجێکتە ئێستاکە

Common mistake: name = name;هەڵەی باو: ⁦name = name;⁩

Without this, both sides of name = name; are the parameter: it is assigned to itself and the field is never touched. javac compiles this without a word, even with -Xlint:all:

بەبێ this، هەردوو لای name = name; : دەدرێتەوە بە خۆی و هەرگیز دەست لە نادرێت. javac بەبێ هیچ وشەیەک کۆمپایلی دەکات، تەنانەت بە -Xlint:allـیش:

NoThis.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Student {
    String name;
    int mark;

    Student(String name, int mark) {
        name = name;
        mark = mark;
    }
}

public class NoThis {
    public static void main(String[] args) {
        Student rebin = new Student("Rebin", 78);
        System.out.println(rebin.name + " has " + rebin.mark + " marks.");
    }
}
Inside the constructor, name = name;: an arrow loops from the parameter name ("Rebin") back to itself — the parameter gets its own value back. Beside it, the object's fields name null and mark 0 are untouched, and the program prints null has 0 marks. Notes: javac compiles it without a warning (even with -Xlint:all); fix: this.name = name;لە ناو دروستکەرەکەدا، name = name;: تیرێک لە پارامیتەری name ("Rebin")ـەوە دەگەڕێتەوە بۆ خۆی — پارامیتەرەکە نرخەکەی خۆی وەردەگرێتەوە. لە تەنیشتیەوە، تایبەتمەندییەکانی ئۆبجێکتەکە، name null و mark 0، دەستیان لێ نەدراوە و بەرنامەکە null has 0 marks. چاپ دەکات. تێبینییەکان: javac بەبێ ئاگادارکردنەوە کۆمپایلی دەکات (تەنانەت بە -Xlint:all)؛ چارەسەر: this.name = name;
Without this, the field is never setبەبێ this، هەرگیز نرخ وەرناگرێتCêIT

this exists only where there is an object. In a static method such as main, javac answers non-static variable this cannot be referenced from a static context.

this تەنیا لەو شوێنە هەیە کە هەبێت. لە staticـی وەک main، javac وەڵام دەداتەوە: non-static variable this cannot be referenced from a static context.

Several constructorsچەند دروستکەرێک

A class may have several constructors, as long as their parameter lists differ. This is constructor overloading, and Java picks the version by the arguments, exactly as with methods (One name, several methods):

دەتوانێت چەند هەبێت، بە مەرجێک لیستی جیاواز بێت. ئەمە بۆ و Java بەپێی وەشانەکە هەڵدەبژێرێت، ڕێک وەک (یەک ناو، چەند میتۆدێک):

ThreeConstructors.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Student {
    String name;
    int mark;

    Student() {
        name = "Unknown";
        mark = 0;
    }

    Student(String name) {
        this.name = name;
        mark = 0;
    }

    Student(String name, int mark) {
        this.name = name;
        this.mark = mark;
    }

    void printReport() {
        System.out.println(name + " has " + mark + " marks.");
    }
}

public class ThreeConstructors {
    public static void main(String[] args) {
        Student a = new Student();
        Student b = new Student("Hana");
        Student c = new Student("Soran", 64);
        a.printReport();
        b.printReport();
        c.printReport();
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 5-8

No arguments: a stand-in name and mark 0.

بێ : ناوێکی جێگرەوە و نمرەی 0.

Lineدێڕی 10-13

Only a name: the mark starts at 0.

تەنیا ناوێک: نمرەکە بە 0 دەست پێ دەکات.

Two constructors with the same parameter types are not allowed, even with different parameter names: constructor Student(String) is already defined in class Student.

دوو بە هەمان جۆرەکانی ڕێگەپێدراو نین، تەنانەت ئەگەر ناوی جیاواز بێت: constructor Student(String) is already defined in class Student.

Three calls and three constructors. new Student() goes to Student() and gives Unknown, 0; new Student("Hana") goes to Student(String name) and gives Hana, 0; new Student("Soran", 64) goes to Student(String name, int mark) and gives Soran, 64. Note: same name, different parameter lists: constructor overloading.سێ بانگکردن و سێ دروستکەر. new Student() دەچێت بۆ Student() و Unknown، 0 دەدات؛ new Student("Hana") دەچێت بۆ Student(String name) و Hana، 0 دەدات؛ new Student("Soran", 64) دەچێت بۆ Student(String name, int mark) و Soran، 64 دەدات. تێبینی: هەمان ناو و لیستی پارامیتەری جیاواز: فرەپێناسەکردنی میتۆد بۆ دروستکەرەکان.
Java picks the constructor by the argumentsJava بەپێی هەڵدەبژێرێتCêIT

Several constructorsچەند دروستکەرێک

this(...): one constructor calls another⁦this(...)⁩: دروستکەرێک بانگی یەکێکی تر دەکات

The three constructors above repeat the same assignments. Instead, let the short ones call the full one with this(...). Now the fields are set in one place only:

سێ سەرەوە هەمان دانانەکان دووپاتە دەکەنەوە. لە جیاتی ئەوە، با بە this(...) بانگی بکەن. ئێستا تەنیا لە یەک شوێندا دادەنرێن:

Chain.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Student {
    String name;
    int mark;

    Student() {
        this("Unknown", 0);
    }

    Student(String name) {
        this(name, 0);
    }

    Student(String name, int mark) {
        this.name = name;
        this.mark = mark;
        System.out.println("Made " + name + " with " + mark);
    }
}

public class Chain {
    public static void main(String[] args) {
        Student a = new Student();
        Student b = new Student("Hana");
        Student c = new Student("Soran", 64);
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 6

Calls Student(String, int) with "Unknown" and 0.

بانگی ⁦Student(String, int)⁩ دەکات بە ⁦"Unknown"⁩ و 0.

Lineدێڕی 10

Calls the same full constructor with the name and 0.

بانگی هەمان دەکات بە ناوەکە و 0.

this(...) must be the first statement of a constructor:

this(...) دەبێت یەکەم بێت لە :

ChainLate.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Student {
    String name;
    int mark;

    Student(String name) {
        System.out.println("Starting");
        this(name, 0);
    }

    Student(String name, int mark) {
        this.name = name;
        this.mark = mark;
    }
}

public class ChainLate {
    public static void main(String[] args) {
        Student b = new Student("Hana");
    }
}
Left: Student() { this("Unknown", 0); } and Student(String name) { this(name, 0); }, with arrows to the right box, the full constructor Student(String name, int mark) { this.name = name; this.mark = mark; System.out.println("Made " + name + " with " + mark); } — the one place that sets the fields. Notes: real run: Made Unknown with 0, Made Hana with 0, Made Soran with 64; this(...) must be the first statement of the constructor.لای چەپ: Student() { this("Unknown", 0); } و Student(String name) { this(name, 0); }، بە تیر بۆ سندووقی لای ڕاست، دروستکەرە تەواوەکە Student(String name, int mark) { this.name = name; this.mark = mark; System.out.println("Made " + name + " with " + mark); } — تەنیا یەک شوێن کە تایبەتمەندییەکان دادەنێت. تێبینییەکان: جێبەجێکردنی ڕاستەقینە: Made Unknown with 0، Made Hana with 0، Made Soran with 64؛ this(...) دەبێت یەکەم ڕستە بێت لە دروستکەرەکەدا.
The short constructors call the full one بانگی دەکەنCêIT

A static counter of created objectsژمێرەرێکی static بۆ ئەو ئۆبجێکتانەی دروست کراون

A constructor runs once for every new object, so it is the right place to count them. A static field keeps one shared count (static members), and each object copies the new count into its own id:

بۆ هەر نوێ یەک جار جێبەجێ دەبێت، بۆیە شوێنی گونجاوە بۆ ژماردنیان. static یەک ژمارەی هاوبەش هەڵدەگرێت (ئەندامە ستاتیکەکان) و هەر ژمارە نوێیەکە دەخاتە ناو idـی خۆی:

CountStudents.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Student {
    static int count = 0;   // shared by all students
    int id;                 // each student has their own
    String name;

    Student(String name) {
        count++;
        id = count;
        this.name = name;
    }
}

public class CountStudents {
    public static void main(String[] args) {
        System.out.println("Students so far: " + Student.count);
        Student a = new Student("Aram");
        Student b = new Student("Shilan");
        Student c = new Student("Karwan");
        System.out.println(a.name + " has id " + a.id);
        System.out.println(b.name + " has id " + b.id);
        System.out.println(c.name + " has id " + c.id);
        System.out.println("Students so far: " + Student.count);
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2-3

One count for the whole class; one id in every object.

یەک count بۆ هەموو ؛ یەک id لە هەر .

Lineدێڕی 7-8

Every new object adds one, then keeps the new number as its id.

هەر نوێ یەکێک زیاد دەکات، پاشان ژمارە نوێیەکە وەک idـی خۆی هەڵدەگرێت.

Animation. The class Student has static int count, shown in an orange box, and the instance fields int id and String name; its constructor runs count++; id = count; this.name = name;. 1: Students so far: 0, no objects yet. 2: new Student("Aram") makes count 1, and object a gets id 1. 3: new Student("Shilan") makes count 2, and b gets id 2. 4: new Student("Karwan") makes count 3, and c gets id 3. Last frame: Students so far: 3 — one shared count, three objects with their own ids.
Animation. The class Student has static int count, shown in an orange box, and the instance fields int id and String name; its constructor runs count++; id = count; this.name = name;. 1: Students so far: 0, no objects yet. 2: new Student("Aram") makes count 1, and object a gets id 1. 3: new Student("Shilan") makes count 2, and b gets id 2. 4: new Student("Karwan") makes count 3, and c gets id 3. Last frame: Students so far: 3 — one shared count, three objects with their own ids.
One shared count, an own id in every objectیەک countـی هاوبەش، idـێکی تایبەت لە هەر CêIT

final fields: set onceتایبەتمەندییەکانی final: یەک جار نرخ وەردەگرن

A field marked final gets its value once, normally in the constructor, and can never change afterwards; it suits a student number. static final makes a for the whole class, written in capitals (Constants):

کە بە final نیشانە کراوە یەک جار نرخ وەردەگرێت (زۆرجار لە ) و دواتر هەرگیز ناگۆڕێت؛ بۆ ژمارەی قوتابی گونجاوە. static final بۆ هەموو دروست دەکات کە بە پیتی گەورە دەنووسرێت (نەگۆڕەکان):

FinalId.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Student {
    static final int MAX_MARK = 100;
    final int id;
    String name;

    Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

public class FinalId {
    public static void main(String[] args) {
        Student lana = new Student(2041, "Lana");
        lana.name = "Lana K.";
        System.out.println(lana.id + " " + lana.name);
        System.out.println("Highest mark: " + Student.MAX_MARK);
    }
}

javac checks both rules. Changing a final field gives cannot assign a value to final variable id. A constructor that forgets it gives variable id might not have been initialized, and a class with no constructor at all gives variable id not initialized in the default constructor.

javac هەردوو یاساکە دەپشکنێت. گۆڕینی final cannot assign a value to final variable id دەدات. کە لەبیری بکات variable id might not have been initialized دەدات و کە هیچ نەبێت variable id not initialized in the default constructor دەدات.

The class Student with static final int MAX_MARK = 100 (a constant for the whole class), final int id and String name. The variable lana points to an object with final int id 2041 (a padlock) and String name "Lana K.". Three lines: lana.name = "Lana K."; allowed, name is not final (ticked); lana.id = 2042; cannot assign a value to final variable id (crossed); Student.MAX_MARK = 120; a constant cannot change either (crossed).کلاسی Student بە static final int MAX_MARK = 100 (نەگۆڕێک بۆ هەموو کلاسەکە)، final int id و String name. گۆڕاوی lana ئاماژە بۆ ئۆبجێکتێک دەکات بە final int id 2041 (قوفڵێک) و String name "Lana K.". سێ دێڕ: lana.name = "Lana K."; ڕێگەپێدراوە، name final نییە (✓)؛ lana.id = 2042; cannot assign a value to final variable id (✗)؛ Student.MAX_MARK = 120; نەگۆڕێکیش ناگۆڕێت (✗).
final: a field that gets its value oncefinal: کە تەنیا یەک جار نرخ وەردەگرێتCêIT

Access modifiers: who may use whatدیاریکەرەکانی دەستڕاگەیشتن: کێ دەتوانێت چی بەکار بهێنێت

The words public and private before a class, field, method or constructor are : they decide which code may use it. Java has four levels; the fourth is writing no word at all, called package-private:

وشەکانی public و private لە پێش ، ، یان : بڕیار دەدەن کام کۆد بۆی هەیە بەکاری بهێنێت. Java چوار ئاستی هەیە؛ چوارەمیان نەنووسینی هیچ وشەیەکە، کە پێی دەڵێن package-private:

Who may use a member (as in The Java Tutorials, Controlling Access)کێ دەتوانێت ئەندامێک بەکار بهێنێت (وەک The Java Tutorials، Controlling Access)
ModifierدیاریکەرIts own class خۆیSame packageهەمان Subclass in another package لە ترداEverywhereهەموو شوێنێک
public✓✓✓✓
protected✓✓✓✗
no modifier (package-private)بێ دیاریکەر ⁦(package-private)⁩✓✓✗✗
private✓✗✗✗

A top-level class can only be public or package-private. protected matters once classes inherit from each other: protected: open to subclasses. A good rule from the Java Tutorials: choose the most restrictive level that works, make fields private, and avoid public fields except constants.

ئاستی سەرەوە تەنیا دەتوانێت public یان ⁦package-private⁩ بێت. protected کاتێک گرنگ دەبێت کە لە یەکتری وەربگرن: protected: کراوەیە بۆ کلاسەکانی منداڵ. یاسایەکی باش لە The Java Tutorialsـەوە: توندترین ئاست هەڵبژێرە کە کار دەکات، بکە بە private و خۆت لە public بپارێزە، جگە لە .

Four nested rings around a box class Student with private int mark;. Innermost, private: only its own class. Then no modifier (package-private): only the same package. Then protected: the same package plus subclasses. Outermost, public: every class, everywhere.چوار بازنەی لە ناو یەک بە دەوری سندووقی class Student کە private int mark;ـی تێدایە. ناوەوەترین، private: تەنیا کلاسەکەی خۆی. پاشان بێ دیاریکەر (package-private): تەنیا هەمان پاکێج. پاشان protected: هەمان پاکێج لەگەڵ کلاسەکانی منداڵ. دەرەوەترین، public: هەموو کلاسێک، لە هەموو شوێنێک.
From private (smallest) to public (everyone)لە private (بچووکترین)ـەوە تا public (هەمووان)CêIT

Access modifiers: who may use whatدیاریکەرەکانی دەستڕاگەیشتن: کێ دەتوانێت چی بەکار بهێنێت

private: only inside its own classprivate: تەنیا لە ناو کلاسەکەی خۆیدا

Mark the fields of Student as private (the whole class is on the Encapsulation screen), and another class can no longer touch them directly:

Student بکە بە private (هەموو لە شاشەی کەپسوولکردندایە) و ئیتر هیچ تر ناتوانێت ڕاستەوخۆ دەستیان لێ بدات:

School.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class School {
    public static void main(String[] args) {
        Student aram = new Student("Aram");
        aram.mark = 120;
        System.out.println(aram.name);
    }
}

Methods of Student itself still use these fields freely; every other class has to go through the class's public methods.

خودی Student هێشتا بە ئازادی ئەم بەکار دەهێنن؛ هەموو تر دەبێت لە ڕێگەی publicـی ئەو بڕوات.

Access modifiers: who may use whatدیاریکەرەکانی دەستڕاگەیشتن: کێ دەتوانێت چی بەکار بهێنێت

No modifier: package accessبێ دیاریکەر: دەستڕاگەیشتنی پاکێج

A member with no modifier can be used by every class in the same package, and by no other. Classes in one folder without a package line share the unnamed package, which is why the last lesson could use plain fields. With real packages (Your own package) the limit shows:

ئەندامێک کە هیچ دیاریکەرێکی نەبێت هەموو هەمان دەتوانێت بەکاری بهێنێت و هیچ تر نا. ئەو لە یەک و دێڕی packageیان نییە بێناوەکە بەش دەکەن، هەر بۆیە وانەی پێشوو دەیتوانی ئاسایی بەکار بهێنێت. بە ڕاستەقینە (پاکێجی خۆت) سنوورەکە دەردەکەوێت:

school/Student.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
package school;

public class Student {
    public String name;
    int mark;

    public Student(String name, int mark) {
        this.name = name;
        this.mark = mark;
    }
}
app/Main.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
package app;

import school.Student;
import school.Teacher;

public class Main {
    public static void main(String[] args) {
        Student s = new Student("Dilan", 74);
        Teacher.check(s);
        System.out.println(s.name);
        System.out.println(s.mark);
    }
}
Two packages. package school holds Student (public String name, and int mark with no modifier: package access) and Teacher, whose println(s.mark); is allowed (same package). package app holds Main: println(s.name); is allowed (public), but println(s.mark); is crossed out (not from another package). Below: error: mark is not public in Student; cannot be accessed from outside package.دوو پاکێج. package school کلاسی Student (public String name و int mark بێ دیاریکەر: دەستڕاگەیشتنی پاکێج) و Teacher لەخۆ دەگرێت، کە println(s.mark);ـەکەی ڕێگەپێدراوە (هەمان پاکێج). package app کلاسی Main لەخۆ دەگرێت: println(s.name); ڕێگەپێدراوە (public)، بەڵام println(s.mark); بە خەت سڕاوەتەوە (نەک لە پاکێجێکی ترەوە). لە خوارەوە: error: mark is not public in Student; cannot be accessed from outside package.
Package access: the same package yes, another package noدەستڕاگەیشتنی : هەمان بەڵێ، تر نەخێرCêIT

Other modifiers: static, final, abstract …دیاریکەرەکانی تر: static، final، abstract …

Some modifiers say nothing about access; W3Schools calls them non-access modifiers. The three you will use most are static, final and abstract:

هەندێک دیاریکەر هیچ لەبارەی دەستڕاگەیشتن نالێن؛ ⁦W3Schools⁩ پێیان دەڵێت non-access modifiers. ئەو سێیەی زیاتر بەکاریان دەهێنیت static، final و abstractـن:

ModifierدیاریکەرOn a classلەسەر On a field or methodلەسەر یان
staticnot for a top-level classبۆ ئاستی سەرەوە نییەbelongs to the class, not to each objectهی ، نەک هی هەر
finalno class may inherit from itهیچ ناتوانێت لێ وەربگرێتa field gets its value once; a method cannot be overridden یەک جار نرخ وەردەگرێت؛ ناتوانرێت دووپاتە پێناسە بکرێتەوە
abstractno objects can be made from itهیچ لێی دروست ناکرێتa method with no body; a subclass writes it بێ جەستە؛ دەینووسێت
transient—skipped when an object is saved (serialization)کاتی هەڵگرتنی ⁦(serialization)⁩ لەبەرچاو ناگیرێت
synchronized—only one thread at a time may run the methodلە هەر کاتێکدا تەنیا یەک thread دەتوانێت جێبەجێ بکات
volatile—every thread sees the newest value written to it (for threads)هەموو threadـێک دوایین دەبینێت کە تێیدا نووسراوە (بۆ threadـەکان)

abstract is taught in Abstract classes and abstract methods, and final methods and classes in final classes and methods. The last three belong to threads and to saving objects, which this course only names.

abstract لە کلاسە ڕووتەکان و میتۆدە ڕووتەکان دەخوێنرێت و و final لە کلاسەکان و میتۆدەکانی final. سێ دوایینەکە هی threadـەکان و هەڵگرتنی کە ئەم کۆرسە تەنیا ناویان دەبات.

Encapsulation: private fields, public methodsکەپسوولکردن: تایبەتمەندییەکانی private، میتۆدەکانی public

Definitionپێناسە

Keeping an object's data and the methods that use it together in one , and hiding the data: the fields are private, and other code reaches them only through methods such as a and a . The class can then check every change, for example refuse a mark above 100.

هێشتنەوەی و ئەو بەکاری دەهێنن پێکەوە لە یەک ، لەگەڵ شاردنەوەی دراوەکە: privateـن و کۆدی تر تەنیا لە ڕێگەی وەک و پێیان دەگات. بەم شێوەیە دەتوانێت هەموو گۆڕانکارییەک بپشکنێت، بۆ نموونە نمرەیەکی سەرووی ⁦100⁩ ڕەت بکاتەوە.

In practice: keep the fields private and let other code reach them only through public methods. A method that gives a field's value back is a ; one that changes it is a . By convention they are called get or set plus the field's name with a capital letter, getName() and setMark(int); a boolean getter usually starts with is, as in isPassed():

لە پراکتیکدا: private بهێڵەوە و با کۆدی تر تەنیا لە ڕێگەی publicـەوە پێیان بگات. کە دەگەڕێنێتەوە ؛ ئەوەی دەیگۆڕێت . بە نەریت ناویان get یان setـە لەگەڵ ناوی بە پیتی گەورەی سەرەتا: getName() و setMark(int)؛ boolean زۆرجار بە is دەست پێ دەکات، وەک isPassed():

Student.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Student {
    private String name;
    private int mark;

    public Student(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public int getMark() {
        return mark;
    }

    public void setMark(int mark) {
        if (mark >= 0 && mark <= 100) {
            this.mark = mark;
        } else {
            System.out.println("Refused: " + mark + " is not between 0 and 100.");
        }
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2-3

private: only Student's own methods may touch these fields.

private: تەنیا خودی Student دەتوانن دەست لەم بدەن.

Lineدێڕی 9-15

Getters: public methods that give the values back.

: public کە دەگەڕێننەوە.

Lineدێڕی 17-23

The setter: the only way to change mark, and it checks the value.

: تاکە ڕێگەی گۆڕینی mark، کە دەپشکنێت.

A capsule labelled Student holds the fields private String name and private int mark, each with a padlock. Its walls have three doors, the public methods getName(), getMark() and setMark(int). Outside: aram.getMark() reaches getMark() (ticked) and aram.setMark(85) reaches setMark(int) (ticked), but aram.mark = 120; stops at the wall (crossed) with mark has private access in Student.کەپسوولێک بە ناوی Student تایبەتمەندییەکانی private String name و private int mark هەڵدەگرێت، هەر یەکەیان بە قوفڵێکەوە. دیوارەکانی سێ دەرگایان هەیە، میتۆدەکانی public: getName()، getMark() و setMark(int). لە دەرەوە: aram.getMark() دەگاتە getMark() (✓) و aram.setMark(85) دەگاتە setMark(int) (✓)، بەڵام aram.mark = 120; لە دیوارەکە دەوەستێت (✗) بە mark has private access in Student.
Encapsulation: private data inside, public methods as the doors: private لە ناوەوە، public وەک دەرگاCêIT

Encapsulation: private fields, public methodsکەپسوولکردن: تایبەتمەندییەکانی private، میتۆدەکانی public

A setter can check the valueمیتۆدی دانان دەتوانێت نرخەکە بپشکنێت

Because no other class can write aram.mark = 120;, every change goes through setMark, and setMark can refuse a mark outside 0–100. Checking a value before you use it is :

چونکە هیچ تر ناتوانێت aram.mark = 120; بنووسێت، هەموو گۆڕانکارییەک بە setMarkـدا تێدەپەڕێت و setMark دەتوانێت نمرەیەک لە دەرەوەی ⁦0–100⁩ ڕەت بکاتەوە. پشکنینی پێش بەکارهێنانی :

Marks.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Marks {
    public static void main(String[] args) {
        Student aram = new Student("Aram");
        aram.setMark(85);
        aram.setMark(120);
        aram.setMark(-5);
        System.out.println(aram.getName() + ": " + aram.getMark());
    }
}
setMark(85) and setMark(120) arrive at a diamond inside setMark that asks 0 <= mark <= 100 ?. For 85 the answer is yes: this.mark = mark; stores 85 in aram's mark (ticked). For 120 the answer is no: the program prints Refused: 120 is not between 0 and 100. and the field is not changed — aram's mark stays 85.setMark(85) و setMark(120) دەگەنە چوارگۆشەیەکی لار لە ناو setMark کە دەپرسێت 0 <= mark <= 100 ?. بۆ 85 وەڵامەکە بەڵێیە: this.mark = mark; 85 لە markـی aram هەڵدەگرێت (✓). بۆ 120 وەڵامەکە نەخێرە: بەرنامەکە Refused: 120 is not between 0 and 100. چاپ دەکات و تایبەتمەندییەکە ناگۆڕێت — نمرەی aram هەر 85 دەمێنێتەوە.
A setter checks before it stores پێش هەڵگرتن دەپشکنێتCêIT

Encapsulation: private fields, public methodsکەپسوولکردن: تایبەتمەندییەکانی private، میتۆدەکانی public

Why encapsulation paysبۆچی کەپسوولکردن سوودی هەیە

  • Control: the class decides which values are allowed, so a Student can never hold a mark of 120.
  • Read-only or write-only fields: give a getter and no setter (a student number), or the other way round.
  • Freedom to change the inside: store the mark as a double, or keep a history of marks, while other classes keep calling the same getMark().
  • Safer data: code far away cannot break an object, and when a value is wrong you look in one class.
  • کۆنترۆڵ: بڕیار دەدات کام ڕێگەپێدراون، بۆیە هەرگیز Studentـێک نمرەی ⁦120⁩ی نابێت.
  • تەنیا-خوێندنەوە یان تەنیا-نووسین: بدە و نا (ژمارەی قوتابی)، یان پێچەوانەکەی.
  • ئازادیی گۆڕینی ناوەوە: نمرەکە وەک double هەڵبگرە، یان مێژووی نمرەکان بپارێزە، لە کاتێکدا تر هەر هەمان getMark() بانگ دەکەن.
  • سەلامەتتر: کۆدێکی دوور ناتوانێت تێک بدات و کاتێک هەڵەیە تەنیا لە یەک دەگەڕێیت.

Methods can be private too: a helper that only the class itself needs stays hidden, and the public methods are the class's promise to everyone else.

دەتوانن private بن: یاریدەدەر کە تەنیا خودی پێویستی پێیەتی شاراوە دەمێنێتەوە و publicـەکان بەڵێنی بە هەموو ئەوانی تر.

Extra: recordsزیادە: record

Common mistakesهەڵە باوەکان

Every message below is the real text from javac or java 17 for the programs of this lesson.

هەموو پەیامەکانی خوارەوە دەقی ڕاستەقینەی javac یان javaـی ⁦17⁩ـن بۆ ئەم وانەیە.

MistakeهەڵەWhat javac or java saysjavac یان java چی دەڵێتFixچارەسەر
void before a constructorvoid لە پێش constructor Student in class Student cannot be applied to given types; required: no arguments found: String,intRemove void: a constructor has no return typevoid لابدە: نییە
name = name; in a constructorname = name; لە No error: the program prints null has 0 marks.هیچ هەڵەیەک نییە: null has 0 marks. چاپ دەکاتWrite this.name = name;بنووسە this.name = name;
new Student() after writing Student(String, int)new Student() دوای نووسینی Student(String, int)constructor Student in class Student cannot be applied to given types; required: String,int found: no argumentsPass the arguments, or write Student() yourself بنێرە، یان خۆت Student() بنووسە
this(...) after another statementthis(...) دوای ترcall to this must be first statement in constructorMake this(...) the first line of the constructor (Java 25 and newer allow statements before it that do not use the object)this(...) بکە بە یەکەم دێڕی (لە ⁦Java 25⁩ـەوە هەر کە بەکار نەهێنێت دەتوانێت پێشی بکەوێت)
Two constructors with the same parameter typesدوو بە هەمان جۆرەکانی constructor Student(String) is already defined in class StudentChange the parameter types, or keep one constructorجۆرەکانی بگۆڕە، یان یەک بهێڵەوە
this inside mainthis لە ناو mainnon-static variable this cannot be referenced from a static contextUse an object variable: Student s = new Student(…); s.name بەکار بهێنە: Student s = new Student(…); s.name
Changing a final fieldگۆڕینی finalcannot assign a value to final variable idSet it once, in the constructorیەک جار دایبنێ، لە
A constructor that forgets a final field کە final لەبیر دەکاتvariable id might not have been initializedAssign the field in every constructorلە هەموو دابنێ
Using a private field from another classبەکارهێنانی private لە ترەوەmark has private access in StudentCall the getter or the setter: aram.getMark() یان بانگ بکە: aram.getMark()
A package-private field from another package ⁦package-private⁩ لە ترەوەmark is not public in Student; cannot be accessed from outside packageAdd a public getter (a public field is rarely right) public زیاد بکە ( public کەم جار دروستە)
A setter that does not check کە ناپشکنێتNo error: setMark(120) stores 120هیچ هەڵەیەک نییە: setMark(120) ⁦120⁩ هەڵدەگرێتCheck the value in the setter: if (mark >= 0 && mark <= 100)لە بپشکنە: if (mark >= 0 && mark <= 100)

Practiceڕاهێنان

ExerciseڕاهێنانA bank accountهەژمارێکی بانک

Write BankAccount with a private final owner and a private balance in Iraqi dinars, set by a constructor that takes the owner. deposit(int) accepts only amounts above 0, withdraw(int) refuses amounts above the balance, and getters give both fields. Test: deposit 250000, withdraw 100000, withdraw 500000, deposit −20-20.

BankAccount بنووسە بە ownerـێکی private final و balanceـێکی private بە دیناری عێراقی، کە دایدەنێت و خاوەنەکە وەردەگرێت. deposit(int) تەنیا بڕی سەرووی 0 وەردەگرێت، withdraw(int) بڕی سەرووی باڵانس ڕەت دەکاتەوە و هەردوو دەگەڕێننەوە. تاقیکردنەوە: ⁦250000⁩ دابنێ، ⁦100000⁩ دەربهێنە، ⁦500000⁩ دەربهێنە، −20-20 دابنێ.

Hintئاماژە

Two checks in withdraw: amount <= 0, and amount > balance.

لە withdrawـدا دوو پشکنین: ⁦amount <= 0⁩ و ⁦amount > balance⁩.

Show answerوەڵامەکە پیشان بدە
Bank.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class BankAccount {
    private final String owner;
    private int balance;   // in Iraqi dinars

    BankAccount(String owner) {
        this.owner = owner;
    }

    public String getOwner() {
        return owner;
    }

    public int getBalance() {
        return balance;
    }

    public void deposit(int amount) {
        if (amount > 0) {
            balance = balance + amount;
        } else {
            System.out.println("Refused: deposit must be more than 0.");
        }
    }

    public void withdraw(int amount) {
        if (amount <= 0) {
            System.out.println("Refused: withdraw must be more than 0.");
        } else if (amount > balance) {
            System.out.println("Refused: only " + balance + " IQD in the account.");
        } else {
            balance = balance - amount;
        }
    }
}

public class Bank {
    public static void main(String[] args) {
        BankAccount acc = new BankAccount("Shilan");
        acc.deposit(250000);
        acc.withdraw(100000);
        acc.withdraw(500000);
        acc.deposit(-20);
        System.out.println(acc.getOwner() + ": " + acc.getBalance() + " IQD");
    }
}
ExerciseڕاهێنانThree constructors, one placeسێ دروستکەر، یەک شوێن

Write Rectangle with final width and height and three constructors: Rectangle() (1 × 1), Rectangle(int side) (a square) and Rectangle(int width, int height). Only the last one may assign the fields; the others use this(...). Add area() and toString().

Rectangle بنووسە بە width و heightـی final و سێ : Rectangle() ⁦(1 × 1)⁩، Rectangle(int side) (چوارگۆشە) و Rectangle(int width, int height). تەنیا دوایینیان دەتوانێت دابنێت؛ ئەوانی تر this(...) بەکار دەهێنن. area() و toString() زیاد بکە.

Show answerوەڵامەکە پیشان بدە
Rooms.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Rectangle {
    private final int width;
    private final int height;

    Rectangle() {
        this(1, 1);
    }

    Rectangle(int side) {
        this(side, side);
    }

    Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }

    int area() {
        return width * height;
    }

    @Override
    public String toString() {
        return width + " x " + height + " = " + area();
    }
}

public class Rooms {
    public static void main(String[] args) {
        System.out.println(new Rectangle());
        System.out.println(new Rectangle(4));
        System.out.println(new Rectangle(5, 3));
    }
}
ExerciseڕاهێنانFind the two bugsدوو باگەکە بدۆزەرەوە

This tea-house class does not compile. Find both bugs (one hides behind the other) and fix them.

ئەم چایخانەیە کۆمپایل نابێت. هەردوو بدۆزەرەوە (یەکێکیان لە پشت ئەوی ترەوە خۆی شاردۆتەوە) و چاکیان بکە.

Cafe.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Tea {
    String kind;
    int price;

    void Tea(String kind, int price) {
        kind = kind;
        price = price;
    }
}

public class Cafe {
    public static void main(String[] args) {
        Tea t = new Tea("black", 500);
        System.out.println(t.kind + ": " + t.price + " IQD");
    }
}
Show answerوەڵامەکە پیشان بدە

Bug 1: void Tea(...) is a method, so new Tea("black", 500) finds no constructor. Bug 2, seen after removing void: kind = kind; assigns the parameters to themselves; write this.kind = kind; and this.price = price;.

1: void Tea(...) ، بۆیە new Tea("black", 500) هیچ نادۆزێتەوە. 2، کە دوای لابردنی void دەردەکەوێت: kind = kind; دەداتەوە بە خۆیان؛ بنووسە this.kind = kind; و this.price = price;.

Cafe.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Tea {
    String kind;
    int price;

    Tea(String kind, int price) {
        this.kind = kind;
        this.price = price;
    }
}

public class Cafe {
    public static void main(String[] args) {
        Tea t = new Tea("black", 500);
        System.out.println(t.kind + ": " + t.price + " IQD");
    }
}
ExerciseڕاهێنانA checked temperatureپلەی گەرمییەکی پشکنراو

Write Temperature with a private celsius, a setter that refuses anything colder than −273.15-273.15 °C, a getter, and a computed getter getFahrenheit() (F=C×9/5+32F = C \times 9 / 5 + 32). Try 41.5 for a Hawler summer day, then −300-300.

Temperature بنووسە بە celsiusـێکی private، کە هەر شتێکی ساردتر لە −273.15-273.15 °C ڕەت دەکاتەوە، و ژمێردراو getFahrenheit() (F=C×9/5+32F = C \times 9 / 5 + 32). ⁦41.5⁩ بۆ ڕۆژێکی هاوینی هەولێر تاقی بکەرەوە، پاشان −300-300.

Show answerوەڵامەکە پیشان بدە
Weather.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Temperature {
    private double celsius;

    public double getCelsius() {
        return celsius;
    }

    public double getFahrenheit() {
        return celsius * 9 / 5 + 32;
    }

    public void setCelsius(double celsius) {
        if (celsius >= -273.15) {
            this.celsius = celsius;
        } else {
            System.out.println("Refused: nothing is colder than -273.15 C.");
        }
    }
}

public class Weather {
    public static void main(String[] args) {
        Temperature hawler = new Temperature();
        hawler.setCelsius(41.5);
        System.out.println(hawler.getCelsius() + " C = " + hawler.getFahrenheit() + " F");
        hawler.setCelsius(-300);
        System.out.println(hawler.getCelsius() + " C");
    }
}

getFahrenheit() has no field of its own: it is computed from celsius each time. Other classes cannot tell the difference, which is the freedom that encapsulation gives.

getFahrenheit() هیچ خۆی نییە: هەر جارێک لە celsius دەژمێردرێت. تر جیاوازییەکە نازانن، ئەمە ئەو ئازادییەیە کە دەیبەخشێت.

ExerciseڕاهێنانA queue-ticket machineئامێری بلیتی ڕیز

At a bank in Silêmanî every customer takes a numbered ticket. Write Ticket with a private static counter and a private final number set in the constructor, a getter, and a static method issued(). Make three tickets and print the third number, the first number and how many were issued.

لە بانکێکی سلێمانیدا هەر کڕیارێک بلیتێکی ژمارەدار وەردەگرێت. Ticket بنووسە بە private static و numberـێکی private final کە لە دادەنرێت، و static بە ناوی issued(). سێ بلیت دروست بکە و ژمارەی سێیەم، ژمارەی یەکەم و ژمارەی بلیتە دەرچووەکان چاپ بکە.

Show answerوەڵامەکە پیشان بدە
TicketMachine.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Ticket {
    private static int lastNumber = 0;
    private final int number;

    Ticket() {
        lastNumber++;
        number = lastNumber;
    }

    public int getNumber() {
        return number;
    }

    public static int issued() {
        return lastNumber;
    }
}

public class TicketMachine {
    public static void main(String[] args) {
        Ticket t1 = new Ticket();
        Ticket t2 = new Ticket();
        Ticket t3 = new Ticket();
        System.out.println("Your number: " + t3.getNumber());
        System.out.println("First ticket: " + t1.getNumber());
        System.out.println("Tickets issued: " + Ticket.issued());
    }
}
ExerciseڕاهێنانMake the phone safeمۆبایلەکە سەلامەت بکە

Take the Phone of the last lesson's exercises. Make its fields private, give it a constructor that takes the model (a new phone is full: 100 %), getters, and a setBattery that refuses values outside 0–100.

Phoneـی ڕاهێنانەکانی وانەی پێشوو وەربگرە. بکە بە private، بدەیە کە مۆدێلەکە وەردەگرێت (مۆبایلی نوێ پڕە: ⁦100 %⁩)، و setBatteryـێک کە دەرەوەی ⁦0–100⁩ ڕەت دەکاتەوە.

Show answerوەڵامەکە پیشان بدە
PhoneTest2.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Phone {
    private final String model;
    private int battery;

    Phone(String model) {
        this.model = model;
        battery = 100;   // a new phone comes fully charged
    }

    public String getModel() {
        return model;
    }

    public int getBattery() {
        return battery;
    }

    public void setBattery(int battery) {
        if (battery >= 0 && battery <= 100) {
            this.battery = battery;
        } else {
            System.out.println("Refused: " + battery + "% is not possible.");
        }
    }
}

public class PhoneTest2 {
    public static void main(String[] args) {
        Phone p = new Phone("Rebin's phone");
        p.setBattery(150);
        p.setBattery(65);
        System.out.println(p.getModel() + ": " + p.getBattery() + "%");
    }
}
ExerciseڕاهێنانWhich access?کام دەستڕاگەیشتن؟

Choose a modifier for each member of a Student class: (a) the field mark, (b) the method getMark(), (c) a helper method that only Student itself uses, (d) the highest possible mark, 100, (e) a field that only classes of the same package should use.

بۆ هەر ئەندامێکی Student دیاریکەرێک هەڵبژێرە: ⁦(a)⁩ mark، ⁦(b)⁩ getMark()، ⁦(c)⁩ یاریدەدەر کە تەنیا خودی Student بەکاری دەهێنێت، ⁦(d)⁩ بەرزترین نمرەی گونجاو، ⁦100⁩، ⁦(e)⁩ کە تەنیا هەمان دەبێت بەکاری بهێنن.

Show answerوەڵامەکە پیشان بدە
MemberئەندامModifierدیاریکەرWhyبۆچی
(a)private int mark;every change must go through the setterهەموو گۆڕانکارییەک دەبێت بە تێپەڕێت
(b)public int getMark()other classes need to read the mark تر پێویستیان بە خوێندنەوەی نمرەکەیە
(c)privatenobody else needs itکەسی تر پێویستی پێی نییە
(d)public static final int MAX_MARK = 100;a constant: shared, unchangeable, safe to show: هاوبەش، نەگۆڕاو، پیشاندانی سەلامەتە
(e)no modifierبێ دیاریکەرpackage access: the same package onlyدەستڕاگەیشتنی : تەنیا هەمان

Summaryکورتە

  • A constructor has the class's name and no return type; new runs it once for every object.
  • With no constructor written, javac adds an empty default constructor; write any constructor and it is gone.
  • this.name is the field of the current object; name = name; without this changes nothing.
  • Constructors can be overloaded; this(...), as the first statement, lets them share one full constructor.
  • A static field can count created objects; a final field is set once; static final makes a constant.
  • Access: public everyone, protected package + subclasses, no modifier the same package, private its own class.
  • Encapsulation: private fields, public getters and setters; a setter validates every new value.
  • ناوی و هیچ نییە؛ new بۆ هەر یەک جار جێبەجێی دەکات.
  • ئەگەر هیچ نەنووسرێت، javac بنەڕەتیی بەتاڵ زیاد دەکات؛ هەر بنووسە و نامێنێت.
  • this.name ئێستاکەیە؛ name = name; بەبێ this هیچ ناگۆڕێت.
  • بۆ هەیە؛ this(...)، وەک یەکەم ، ڕێگەیان دەدات یەک تەواو بەش بکەن.
  • static دەتوانێت دروستکراو بژمێرێت؛ final یەک جار دادەنرێت؛ static final دروست دەکات.
  • دەستڕاگەیشتن: public هەمووان، protected + ، بێ دیاریکەر هەمان ، private خۆی.
  • : private، و public؛ هەموو نوێ دەپشکنێت.
Review questionsپرسیارەکانی پێداچوونەوە
How does javac tell a constructor from a method?javac چۆن دروستکەر لە میتۆد جیا دەکاتەوە؟

A constructor has exactly the class's name and no return type. With a return type, even void, it is a method.

ڕێک ناوی و هیچ نییە. بە ، تەنانەت void، دەبێتە .

Why does new Student() stop compiling after you add Student(String, int)?بۆچی دوای زیادکردنی ⁦Student(String, int)⁩، ⁦new Student()⁩ کۆمپایل نابێت؟

javac adds the default constructor only when a class has no constructor at all.

javac تەنیا کاتێک زیاد دەکات کە هیچ نەبێت.

What is the difference between private and no modifier?جیاوازیی نێوان private و بێ دیاریکەر چییە؟

private allows only the class itself; no modifier allows every class of the same package.

private تەنیا ڕێگە بە خودی دەدات؛ بێ دیاریکەر ڕێگە بە هەموو هەمان دەدات.

What does a setter gain over a public field?میتۆدێکی دانان چی زیاتر لە تایبەتمەندییەکی public دەبەخشێت؟

It can check every new value (a mark from 0 to 100) and the inside of the class can change without breaking other code.

دەتوانێت هەموو نوێ بپشکنێت (نمرەیەک لە 0 تا ⁦100⁩) و ناوەوەی دەتوانێت بگۆڕێت بەبێ تێکدانی کۆدی تر.

Lesson complete!وانەکە تەواو بوو!

Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.

Key termsزاراوە سەرەکییەکان

Next lessonوانەی داهاتوو

Inheritance and Polymorphismبۆماوە و فرەشێوەیی

References and further readingسەرچاوەکان و خوێندنەوەی زیاتر

This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.

Appearanceڕووکار

Modeدۆخ
Styleشێواز
Coloursڕەنگەکان

Saved on this device only.تەنیا لەسەر ئەم ئامێرە پاشەکەوت دەکرێت.