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+) وەک زیادە دێت.
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()، پاشان بۆ هەر دێڕێک. دێڕێک لەبیر بکە و بە بێدەنگی دەهێڵێتەوە؛ هیچ شتێک ئاگادارت ناکاتەوە:
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();
}
}$ java ForgotMark Aram has 85 marks. Karwan has 0 marks.
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 دروست بکات جێبەجێ دەبێت. وەک وەردەگرێت و پڕ دەکاتەوە، بۆیە هەموو نوێ لە یەکەم ساتەوە تەواوە.
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 دەیاننووسیت:
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();
}
}$ java FirstConstructor New student: Aram New student: Shilan Aram has 85 marks. Shilan has 92 marks.
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 5-9
The constructor: the class name, two parameters, no return type.
: ناوی ، دوو ، بێ .
- Lineدێڕی 18-19
Each
newruns the constructor once, with its own arguments.هەر
newـێک یەک جار جێبەجێ دەکات، بە خۆی.


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ـە و هیچ خۆی نییە. بانگکردنەکە بە دوو سەرناکەوێت:
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);
}
}$ javac VoidConstructor.java
VoidConstructor.java:13: error: constructor Student in class Student cannot be applied to given types;
Student aram = new Student("Aram", 85);
^
required: no arguments
found: String,int
reason: actual and formal argument lists differ in length
1 errorThe 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ـیش هیچ ئاگادارکردنەوەیەک چاپ ناکات:
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);
}
}$ javac -Xlint:all VoidMethod.java $ java VoidMethod null 0 Aram 85
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)، پیشانی دەدات:
javac Student.java
javap Student$ javac Student.java
$ javap Student
Compiled from "Student.java"
class Student {
java.lang.String name;
int mark;
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() زیاد دەکات ببینە.
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() ئیتر کۆمپایل نابێت:
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();
}
}$ javac DefaultGone.java
DefaultGone.java:14: error: constructor Student in class Student cannot be applied to given types;
Student nobody = new Student();
^
required: String,int
found: no arguments
reason: actual and formal argument lists differ in length
1 errorThe 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) دەنووسێت. یان بنێرە، یان بێ خۆت بنووسە، وەک شاشەی داهاتوو پیشانی دەدات.
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 :
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();
}
}$ java ThisDemo Rebin has 78 marks. Lana has 91 marks.
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.nameandnameare the same field here.لە هیچ ناشارێتەوە، بۆیە لێرەدا
this.nameوnameهەمان .
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ـیش:
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.");
}
}$ javac -Xlint:all NoThis.java $ java NoThis null has 0 marks.
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 بەپێی وەشانەکە هەڵدەبژێرێت، ڕێک وەک (یەک ناو، چەند میتۆدێک):
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();
}
}$ java ThreeConstructors Unknown has 0 marks. Hana has 0 marks. Soran has 64 marks.
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.
Several constructorsچەند دروستکەرێک
this(...): one constructor calls anotherthis(...): دروستکەرێک بانگی یەکێکی تر دەکات
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(...) بانگی بکەن. ئێستا تەنیا لە یەک شوێندا دادەنرێن:
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);
}
}$ java Chain Made Unknown with 0 Made Hana with 0 Made Soran with 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(...) دەبێت یەکەم بێت لە :
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");
}
}$ javac ChainLate.java
ChainLate.java:7: error: call to this must be first statement in constructor
this(name, 0);
^
1 errorA 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ـی خۆی:
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);
}
}$ java CountStudents Students so far: 0 Aram has id 1 Shilan has id 2 Karwan has id 3 Students so far: 3
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ـی خۆی هەڵدەگرێت.


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 بۆ هەموو دروست دەکات کە بە پیتی گەورە دەنووسرێت (نەگۆڕەکان):
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);
}
}$ java FinalId 2041 Lana K. Highest mark: 100
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 دەدات.
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:
| 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 بپارێزە، جگە لە .
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 (هەموو لە شاشەی کەپسوولکردندایە) و ئیتر هیچ تر ناتوانێت ڕاستەوخۆ دەستیان لێ بدات:
public class School {
public static void main(String[] args) {
Student aram = new Student("Aram");
aram.mark = 120;
System.out.println(aram.name);
}
}$ javac School.java Student.java
School.java:4: error: mark has private access in Student
aram.mark = 120;
^
School.java:5: error: name has private access in Student
System.out.println(aram.name);
^
2 errorsMethods 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یان نییە بێناوەکە بەش دەکەن، هەر بۆیە وانەی پێشوو دەیتوانی ئاسایی بەکار بهێنێت. بە ڕاستەقینە (پاکێجی خۆت) سنوورەکە دەردەکەوێت:
package school;
public class Student {
public String name;
int mark;
public Student(String name, int mark) {
this.name = name;
this.mark = mark;
}
}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);
}
}$ javac school/Student.java school/Teacher.java app/Main.java
app/Main.java:11: error: mark is not public in Student; cannot be accessed from outside package
System.out.println(s.mark);
^
1 errorOther 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لەسەر یان |
|---|---|---|
static | not for a top-level classبۆ ئاستی سەرەوە نییە | belongs to the class, not to each objectهی ، نەک هی هەر |
final | no class may inherit from itهیچ ناتوانێت لێ وەربگرێت | a field gets its value once; a method cannot be overridden یەک جار نرخ وەردەگرێت؛ ناتوانرێت دووپاتە پێناسە بکرێتەوە |
abstract | no 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
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():
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، کە دەپشکنێت.
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 ڕەت بکاتەوە. پشکنینی پێش بەکارهێنانی :
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());
}
}$ javac Marks.java Student.java $ java Marks Refused: 120 is not between 0 and 100. Refused: -5 is not between 0 and 100. Aram: 85
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 samegetMark(). - 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,int | Remove 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 arguments | Pass the arguments, or write Student() yourself بنێرە، یان خۆت Student() بنووسە |
this(...) after another statementthis(...) دوای تر | call to this must be first statement in constructor | Make 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 Student | Change the parameter types, or keep one constructorجۆرەکانی بگۆڕە، یان یەک بهێڵەوە |
this inside mainthis لە ناو main | non-static variable this cannot be referenced from a static context | Use an object variable: Student s = new Student(…); s.name بەکار بهێنە: Student s = new Student(…); s.name |
Changing a final fieldگۆڕینی final | cannot assign a value to final variable id | Set it once, in the constructorیەک جار دایبنێ، لە |
A constructor that forgets a final field کە final لەبیر دەکات | variable id might not have been initialized | Assign the field in every constructorلە هەموو دابنێ |
Using a private field from another classبەکارهێنانی private لە ترەوە | mark has private access in Student | Call 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 package | Add 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ڕاهێنان
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 .
BankAccount بنووسە بە ownerـێکی private final و balanceـێکی private بە دیناری عێراقی، کە دایدەنێت و خاوەنەکە وەردەگرێت. deposit(int) تەنیا بڕی سەرووی 0 وەردەگرێت، withdraw(int) بڕی سەرووی باڵانس ڕەت دەکاتەوە و هەردوو دەگەڕێننەوە. تاقیکردنەوە: 250000 دابنێ، 100000 دەربهێنە، 500000 دەربهێنە، دابنێ.
Hintئاماژە
Two checks in withdraw: amount <= 0, and amount > balance.
لە withdrawـدا دوو پشکنین: amount <= 0 و amount > balance.
Show answerوەڵامەکە پیشان بدە
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");
}
}$ java Bank Refused: only 150000 IQD in the account. Refused: deposit must be more than 0. Shilan: 150000 IQD
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وەڵامەکە پیشان بدە
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));
}
}$ java Rooms 1 x 1 = 1 4 x 4 = 16 5 x 3 = 15
This tea-house class does not compile. Find both bugs (one hides behind the other) and fix them.
ئەم چایخانەیە کۆمپایل نابێت. هەردوو بدۆزەرەوە (یەکێکیان لە پشت ئەوی ترەوە خۆی شاردۆتەوە) و چاکیان بکە.
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");
}
}$ javac Cafe.java
Cafe.java:13: error: constructor Tea in class Tea cannot be applied to given types;
Tea t = new Tea("black", 500);
^
required: no arguments
found: String,int
reason: actual and formal argument lists differ in length
1 errorShow 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;.
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");
}
}$ java Cafe black: 500 IQD
Write Temperature with a private celsius, a setter that refuses anything colder than °C, a getter, and a computed getter getFahrenheit() (). Try 41.5 for a Hawler summer day, then .
Temperature بنووسە بە celsiusـێکی private، کە هەر شتێکی ساردتر لە °C ڕەت دەکاتەوە، و ژمێردراو getFahrenheit() (). 41.5 بۆ ڕۆژێکی هاوینی هەولێر تاقی بکەرەوە، پاشان .
Show answerوەڵامەکە پیشان بدە
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");
}
}$ java Weather 41.5 C = 106.7 F Refused: nothing is colder than -273.15 C. 41.5 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 دەژمێردرێت. تر جیاوازییەکە نازانن، ئەمە ئەو ئازادییەیە کە دەیبەخشێت.
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وەڵامەکە پیشان بدە
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());
}
}$ java TicketMachine Your number: 3 First ticket: 1 Tickets issued: 3
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وەڵامەکە پیشان بدە
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() + "%");
}
}$ java PhoneTest2 Refused: 150% is not possible. Rebin's phone: 65%
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) | private | nobody 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;
newruns it once for every object. - With no constructor written, javac adds an empty default constructor; write any constructor and it is gone.
this.nameis the field of the current object;name = name;withoutthischanges nothing.- Constructors can be overloaded;
this(...), as the first statement, lets them share one full constructor. - A static field can count created objects; a
finalfield is set once;static finalmakes a constant. - Access:
publiceveryone,protectedpackage + subclasses, no modifier the same package,privateits 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؛ هەموو نوێ دەپشکنێت.
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زاراوە سەرەکییەکان
Inheritance and Polymorphismبۆماوە و فرەشێوەیی
Related lecturesوانە پەیوەندیدارەکان
- Method Overloading and Scopeفرەپێناسەکردنی میتۆد و مەودا
- Inheritance and Polymorphismبۆماوە و فرەشێوەیی
- Abstract Classes, Interfaces, Inner Classes and Enumsکلاسە ڕووتەکان، نێوبەستەکان، کلاسە ناوەکییەکان و ئینەمەکان
- Packages, import and the Java APIپاکێجەکان، import و APIـی Java
- Exceptions: try, catch and finallyهەڵاوێردەکان: try، catch و finally
- Variables, Names and Constantsگۆڕاوەکان، ناوەکان و نەگۆڕەکان
- Dart Classes, Inheritance and Mixinsکلاسەکان، بۆماوە و میکسینەکان لە Dartـدا
- Project: A Student Marks Managerپڕۆژیلە: بەڕێوەبەری نمرەی قوتابیان
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
- W3Schools: Java Constructors
- W3Schools: Java this Keyword
- W3Schools: Java Modifiers
- W3Schools: Java Non-Access Modifiers
- W3Schools: Java Encapsulation
- The Java Tutorials: Providing Constructors for Your Classes
- The Java Tutorials: Using the this Keyword
- The Java Tutorials: Controlling Access to Members of a Class
- The Java Tutorials: Understanding Class Members (static, constants)
- The Java Tutorials: Declaring Member Variables (private fields, getters and setters)
- Java Language Specification (Java SE 17), §8.8 Constructor Declarations (§8.8.7.1 explicit invocations, §8.8.9 default constructor) and §8.3.1.2 final Fields
- Java Language Specification (Java SE 17), §6.6 Access Control
- JEP 395: Records
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.