JavaJava · Chapterبەش 10 · Lectureوانە 10.1
Classes and Objects: Attributes and Methodsکلاسەکان و ئۆبجێکتەکان: تایبەتمەندییەکان و میتۆدەکان
Object-oriented programming in Java: a class is the plan and objects are made from it with new. Fields hold each object's data and instance methods are its actions, while static members belong to the class. See how a variable holds a reference, how two variables share one object, how objects travel into methods, what null and garbage collection mean, how to compile classes in several files, and why an object prints as Student@6b95977 until you write toString.
لە Javaـدا: نەخشەکەیە و بە new لێی دروست دەکرێن. هەر هەڵدەگرن و ئەو کارانەن کە دەتوانێت بیانکات، بەڵام هی خودی . دەبینیت چۆن هەڵدەگرێت، دوو چۆن یەک بەش دەکەن، چۆن دەچنە ناو ، null و چ واتایەکیان هەیە، ناو چەند چۆن کۆمپایل دەکرێن و بۆچی وەک Student@6b95977 چاپ دەبێت تا toString دەنووسیت.
What you will learnچی فێر دەبیت
- Explain class and object, write a class with fields and methods, and create objects with new.
- Read and change fields with a dot and call instance methods on different objects.
- Tell static members from instance members and fix 'cannot be referenced from a static context'.
- Explain references, null and garbage collection, compile classes in several files, and print objects with toString.
- و ڕوون بکەیتەوە، بە و بنووسیت و بە
newدروست بکەیت. - بە خاڵ بخوێنیتەوە و بیانگۆڕیت و لەسەر جیاواز بانگ بکەیت.
- لە ئەندامەکانی جیا بکەیتەوە و هەڵەی
cannot be referenced from a static contextچاک بکەیت. - ،
nullو ڕوون بکەیتەوە، ناو چەند کۆمپایل بکەیت و بەtoStringچاپ بکەیت.
Programs made of objectsبەرنامەکان لە ئۆبجێکتەکان پێک دێن
So far your programs were main and a few static methods, with the data in separate variables. Real programs describe things: a student has a name and a mark (data), and can give a report or say whether they passed (actions). (OOP) keeps the data of one thing and the actions that use it together, in one . Java is built around this idea: every program you wrote was already a class.
تا ئێستا تۆ main و چەند static بوون و لە جیاجیادا بوو. ڕاستەقینە شتەکان وەسف دەکەن: قوتابییەک ناو و نمرەیەکی هەیە () و دەتوانێت ڕاپۆرت بدات یان بڵێت دەرچووە یان نا (کار). یەک شت و ئەو کارانەی بەکاری دەهێنن پێکەوە لە یەک کۆ دەکاتەوە. Java لەسەر ئەم بیرۆکەیە دروست کراوە: هەموو کە نووسیوتە پێشتر بوو.
The English words (class, object, encapsulation …) are taught in Classes and objects, and the same ideas in Dart in Dart classes. Here you learn them in Java.
وشە ئینگلیزییەکان (class، object، encapsulation …) لە کلاسەکان و ئۆبجێکتەکان دەخوێنرێن و هەمان بیرۆکەکان بە Dart لە کلاسەکانی Dart. لێرەدا بە Java فێریان دەبیت.
Class: the plan; object: a thing made from itکلاس: نەخشەکە؛ ئۆبجێکت: شتێک کە لێی دروست دەکرێت
A describes a kind of thing: which data every object of that kind has and what it can do. It is a plan, not a thing. An is one real thing built from the plan, with its own values; Java also calls it an instance of its class. One Student class can make the objects aram, shilan and karwan, each with its own name and mark. The Python track teaches the same idea in Classes and Objects.
جۆرە شتێک وەسف دەکات: هەر ئەو جۆرە چ هەیە و چی دەتوانێت بکات. نەخشەیە، نەک شت. یەک شتی ڕاستەقینەیە کە لە نەخشەکە دروست کراوە و خۆی هەیە؛ Java پێی دەڵێت نموونەش (instance)ـی . یەک Student دەتوانێت aram، shilan و karwan دروست بکات، هەر یەکەیان ناو و نمرەی خۆی. ڕێڕەوی هەمان بیرۆکە لە کلاسەکان و ئۆبجێکتەکان فێر دەکات.
An architect draws one plan, and builders use it for three houses in three streets. The plan says that every house has an owner and some rooms; each house has its own owner and rooms. Painting one house blue does not paint the others.
ئەندازیارێک یەک نەخشە دەکێشێت و وەستاکان بە هەمان نەخشە سێ خانوو لە سێ شەقامدا دروست دەکەن. نەخشەکە دەڵێت هەموو خانوویەک خاوەنێک و چەند ژوورێکی هەیە؛ هەر خانوویەک خاوەن و ژوورەکانی خۆی هەیە. بۆیاخکردنی خانوویەک بە شین خانووەکانی تر بۆیاخ ناکات.
Where the analogy stops workingسنووری ئەم نموونەیە
A real house takes months; new makes an object at once. And a class holds code too, its methods, not only a drawing.
خانووی ڕاستەقینە چەند مانگێک دەخایەنێت؛ new یەکسەر دروست دەکات. هەروەها کۆدیشی تێدایە، واتە ، نەک تەنیا وێنە.
Class: the plan; object: a thing made from itکلاس: نەخشەکە؛ ئۆبجێکت: شتێک کە لێی دروست دەکرێت
Drawing a class: the class boxکێشانی کلاسێک: سندووقی کلاس
Programmers sketch a class as a box with three parts: the class name, the fields (the data) and the methods (the actions). The drawing comes from UML: a . Database designers draw entities with attributes in a similar way (Entities, Attributes): a Student entity and a Student class often describe the same thing, one for the tables and one for the program.
وەک سندووقێکی سێ بەشی دەکێشن: ناوی ، () و (کارەکان). ئەم وێنەیە لە UMLـەوە هاتووە: . دیزاینەرانی بە بە هەمان شێوە دەکێشن (قەوارەکان، خەسڵەتەکان): Student و Student زۆرجار هەمان شت وەسف دەکەن، یەکێکیان بۆ و ئەوی تریان بۆ .
UML class diagrams: the class box with its name, fields and methods, inheritance, association, aggregation and composition, then object diagrams.
: سندوقی بە ناو، و ، ، پەیوەندیی association، aggregation و composition، پاشان هێڵکاریی .
Watch 1:08–2:15: the class box and its three parts, name, fields and methods; the rest of the video is about the lines between classes.
لە 1:08 تا 2:15 سەیر بکە: سندوقی و سێ بەشەکەی: ناو، و ؛ بەشەکەی دیکەی ڤیدیۆکە لەبارەی هێڵەکانی نێوان .
Write a class, make an object with newکلاسێک بنووسە و بە new ئۆبجێکتێک دروست بکە
Here is a small but complete class: Student with two fields. The program's own class, FirstObject, makes a Student object with new Student() and fills its fields:
ئەمە بچووک بەڵام تەواوە: Student بە دوو . خودی ، FirstObject، بە new Student() Student دروست دەکات و پڕ دەکاتەوە:
class Student {
String name;
int mark;
}
public class FirstObject {
public static void main(String[] args) {
Student aram = new Student();
aram.name = "Aram";
aram.mark = 85;
System.out.println(aram.name + " has " + aram.mark + " marks.");
}
}Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1-4
class Studenthas nopublic, so it may share the file with the public class.nameandmarkare its fields.class Studentهیچpublicـێکی نییە، بۆیە دەتوانێت لەگەڵ public لە یەک بێت.nameوmarkئەون.- Lineدێڕی 8
new Student()makes the object; the variablearamrefers to it.new Student()دروست دەکات؛aramئاماژەی بۆ دەکات.- Lineدێڕی 9-10
A dot reaches a field of the object.
خاڵ دەگاتە .
javac FirstObject.java
ls
java FirstObject$ javac FirstObject.java $ ls FirstObject.class FirstObject.java Student.class $ java FirstObject Aram has 85 marks.
One source file, two class files: javac writes one .class file for every class.
یەک ، دوو class: javac بۆ هەر .class دەنووسێت.


new دروست دەکات؛ تیرێکی بۆی هەڵدەگرێتCêITFields: the data in every objectتایبەتمەندییەکان: دراوەکە لە ناو هەر ئۆبجێکتێکدا
Variables declared inside a class but outside every method are its ; W3Schools calls them class attributes. Every object gets its own copy. Outside the class you reach a field with the object, a dot and the field's name, aram.mark. The same form reads the field, and on the left of = it changes it:
ئەو لە ناو بەڵام لە دەرەوەی هەموو دەناسێنرێن ئەو ؛ W3Schools پێیان دەڵێت class attributes. هەر کۆپیی خۆی وەردەگرێت. لە دەرەوەی بە ، خاڵێک و ناوی پێی دەگەیت: aram.mark. هەمان شێوە دەخوێنێتەوە و لە لای چەپی = دەیگۆڕێت:
class Student {
String name;
int mark;
}
public class ChangeField {
public static void main(String[] args) {
Student aram = new Student();
aram.name = "Aram";
aram.mark = 85;
System.out.println(aram.name + ": " + aram.mark);
aram.mark = aram.mark + 5;
System.out.println(aram.name + ": " + aram.mark);
}
}$ java ChangeField Aram: 85 Aram: 90
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 13
Read the old value (85), add 5, store the result back in the field.
(85) بخوێنەوە، 5ی بخەرە سەر و ئەنجامەکە بخەرەوە ناو .
Fields: the data in every objectتایبەتمەندییەکان: دراوەکە لە ناو هەر ئۆبجێکتێکدا
A new object starts with default valuesئۆبجێکتێکی نوێ بە نرخە بنەڕەتییەکان دەست پێ دەکات
A field that you never set is not empty or random. When new makes an object, Java first gives every field a : null for reference types such as String, 0 for whole numbers, 0.0 for double and false for boolean, just as in a new array (new and default values). A local variable gets no default: reading it before you give it a value is a compile error, variable mark might not have been initialized (No value yet).
کە هەرگیز پێ نەداوە بەتاڵ یان هەڕەمەکی نییە. کاتێک new دروست دەکات، Java سەرەتا دەداتە هەموو : null بۆ وەک String، 0 بۆ ، 0.0 بۆ double و false بۆ boolean، هەر وەک لە نوێدا (new و نرخە بنەڕەتییەکان). هیچ نییە: خوێندنەوەی پێش ئەوەی پێ بدەیت : variable mark might not have been initialized (هێشتا نرخ نییە).
class Student {
String name;
int mark;
double average;
boolean present;
}
public class Defaults {
public static void main(String[] args) {
Student s = new Student();
System.out.println("name = " + s.name);
System.out.println("mark = " + s.mark);
System.out.println("average = " + s.average);
System.out.println("present = " + s.present);
}
}$ java Defaults name = null mark = 0 average = 0.0 present = false
Several objects, each with its own fieldsچەند ئۆبجێکتێک، هەر یەکە و تایبەتمەندییەکانی خۆی
new makes a fresh object every time it runs. Here aram and shilan are two objects of the same class. Changing Shilan's mark does not touch Aram's, because each object keeps its own fields:
new هەر جارێک جێبەجێ بێت نوێ دروست دەکات. لێرەدا aram و shilan دوو هەمان . گۆڕینی نمرەی Shilan دەست لە نمرەی Aram نادات، چونکە هەر خۆی هەڵدەگرێت:
class Student {
String name;
int mark;
}
public class TwoStudents {
public static void main(String[] args) {
Student aram = new Student();
aram.name = "Aram";
aram.mark = 85;
Student shilan = new Student();
shilan.name = "Shilan";
shilan.mark = 92;
shilan.mark = 95;
System.out.println(aram.name + ": " + aram.mark);
System.out.println(shilan.name + ": " + shilan.mark);
}
}$ java TwoStudents Aram: 85 Shilan: 95
Several objects, each with its own fieldsچەند ئۆبجێکتێک، هەر یەکە و تایبەتمەندییەکانی خۆی
Many objects in an ArrayListچەندین ئۆبجێکت لە لیستێکدا
Objects work with everything you know. An ArrayList<Student> keeps many students: a loop makes them, and a for-each loop prints them (Creating an ArrayList, The for-each loop). The list keeps references to the objects, as the picture shows:
لەگەڵ هەموو ئەو شتانەی دەیزانیت کار دەکەن. ArrayList<Student> چەندین قوتابی هەڵدەگرێت: دروستیان دەکات و چاپیان دەکات (دروستکردنی ArrayList، خولی foreach). بۆ هەڵدەگرێت، وەک وێنەکە پیشان دەدات:
import java.util.ArrayList;
class Student {
String name;
int mark;
}
public class StudentList {
public static void main(String[] args) {
String[] names = {"Aram", "Shilan", "Karwan"};
int[] marks = {85, 92, 47};
ArrayList<Student> students = new ArrayList<>();
for (int i = 0; i < names.length; i++) {
Student s = new Student();
s.name = names[i];
s.mark = marks[i];
students.add(s);
}
for (Student s : students) {
System.out.println(s.name + ": " + s.mark);
}
System.out.println(students.size() + " students");
}
}$ java StudentList Aram: 85 Shilan: 92 Karwan: 47 3 students
Methods: what an object can doمیتۆدەکان: ئەوەی ئۆبجێکتێک دەتوانێت بیکات
A method written in the class without static is an instance method: it belongs to each object. Inside it, name and mark mean the fields of the object it was called on. You call it with the object, a dot and the method: aram.printReport(). The same code gives different results for different objects:
کە لە بەبێ static دەنووسرێت (instance method): هی هەر . لە ناویدا، name و mark واتە ئەو لەسەری بانگ کراوە. بە ، خاڵێک و بانگی دەکەیت: aram.printReport(). هەمان کۆد بۆ جیاواز ئەنجامی جیاواز دەدات:
class Student {
String name;
int mark;
void printReport() {
System.out.println(name + " has " + mark + " marks.");
}
boolean passed() {
return mark >= 50;
}
}
public class Report {
public static void main(String[] args) {
Student aram = new Student();
aram.name = "Aram";
aram.mark = 85;
Student karwan = new Student();
karwan.name = "Karwan";
karwan.mark = 47;
aram.printReport();
karwan.printReport();
System.out.println("Aram passed: " + aram.passed());
System.out.println("Karwan passed: " + karwan.passed());
}
}$ java Report Aram has 85 marks. Karwan has 47 marks. Aram passed: true Karwan passed: false
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 5
No
static: an instance method. It uses this object'snameandmark.staticنییە: .nameوmarkـی ئەم بەکار دەهێنێت.- Lineدێڕی 9-11
passed()returns a boolean worked out from the object's own mark.passed()دەگەڕێنێتەوە کە لە نمرەی خودی دەردەهێنرێت.
Methods: what an object can doمیتۆدەکان: ئەوەی ئۆبجێکتێک دەتوانێت بیکات
Methods with parameters can change fieldsمیتۆدەکان بە پارامیتەرەکانەوە دەتوانن تایبەتمەندییەکان بگۆڕن
Instance methods take parameters and return values exactly like the methods you already know (Parameters, Return values). The difference is that they work on the object's own fields. addBonus(5) changes Dilan's mark, and grade() reads it and returns a letter:
ڕێک وەک ئەو پێشتر دەیانزانیت وەردەگرن و دەگەڕێننەوە (پارامیتەرەکان، نرخە گەڕاوەکان). جیاوازییەکە ئەوەیە کە لەسەر خودی کار دەکەن. addBonus(5) نمرەی Dilan دەگۆڕێت و grade() دەیخوێنێتەوە و پیتێک دەگەڕێنێتەوە:
class Student {
String name;
int mark;
void addBonus(int points) {
mark = mark + points;
}
String grade() {
if (mark >= 90) {
return "A";
} else if (mark >= 75) {
return "B";
} else if (mark >= 50) {
return "C";
}
return "F";
}
}
public class Bonus {
public static void main(String[] args) {
Student dilan = new Student();
dilan.name = "Dilan";
dilan.mark = 72;
System.out.println(dilan.name + ": " + dilan.mark + " " + dilan.grade());
dilan.addBonus(5);
System.out.println(dilan.name + ": " + dilan.mark + " " + dilan.grade());
}
}$ java Bonus Dilan: 72 C Dilan: 77 B
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 5-7
A parameter comes in; the method adds it to this object's field.
دێتە ژوورەوە؛ دەیخاتە سەر ئەم .
- Lineدێڕی 9-18
No parameters: the method reads the field and returns a
String.بێ : دەخوێنێتەوە و
Stringـێک دەگەڕێنێتەوە.
A good habit: let an object's own methods change its fields, instead of code far away. The next lesson makes this a rule with private fields (Encapsulation).
خوویەکی باش: با خودی بگۆڕن، نەک کۆدێک لە شوێنێکی دوور. وانەی داهاتوو بە private ئەمە دەکات بە یاسا (کەپسوولکردن).
static members and instance membersئەندامە ستاتیکەکان و ئەندامەکانی ئۆبجێکت
A field or method marked static is a : it belongs to the class itself, not to each object. A static field has one copy that all objects share, and you use it with the class name, Student.passMark. Fields without static are instance fields: one copy in every object. That is also why Math.sqrt(9) needs no object (What the Math class is):
یان کە بە static نیشانە کراوە : هی خودی ، نەک هی هەر . static یەک کۆپیی هەیە کە هەموو بەشی دەکەن و بە ناوی بەکاری دەهێنیت: Student.passMark. ئەو staticیان نییە ئەندامی : کۆپییەک لە هەر . هەر بۆیە Math.sqrt(9) پێویستی بە نییە (کلاسی Math چییە):
class Student {
static int passMark = 50; // one copy, shared by every student
String name; // every student has their own
int mark;
boolean passed() {
return mark >= passMark;
}
static void printRule() {
System.out.println("Pass mark: " + passMark);
}
}
public class PassMark {
public static void main(String[] args) {
Student aram = new Student();
aram.name = "Aram";
aram.mark = 85;
Student karwan = new Student();
karwan.name = "Karwan";
karwan.mark = 47;
Student.printRule();
System.out.println(karwan.name + " passed: " + karwan.passed());
Student.passMark = 45;
Student.printRule();
System.out.println(karwan.name + " passed: " + karwan.passed());
System.out.println(aram.name + " passed: " + aram.passed());
}
}$ java PassMark Pass mark: 50 Karwan passed: false Pass mark: 45 Karwan passed: true Aram passed: true
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
One
passMarkfor the whole class.یەک
passMarkبۆ هەموو .- Lineدێڕی 6-8
An instance method may use the static field.
دەتوانێت static بەکار بهێنێت.
- Lineدێڕی 28
One change, seen by every object.
یەک گۆڕانکاری کە هەموو دەیبینێت.
static members and instance membersئەندامە ستاتیکەکان و ئەندامەکانی ئۆبجێکت
A static method has no objectمیتۆدێکی static هیچ ئۆبجێکتێکی نییە
A static method runs without any object, so 'my name' means nothing there. main is static, so it cannot call an instance method of its own class directly:
static بەبێ هیچ جێبەجێ دەبێت، بۆیە «ناوی من» لەوێدا هیچ واتایەکی نییە. main staticـە، بۆیە ناتوانێت ڕاستەوخۆ بانگی بکات کە لە هەمان :
public class Greeter {
String name = "Hana";
void greet() {
System.out.println("Hello, " + name);
}
public static void main(String[] args) {
greet();
}
}$ javac Greeter.java
Greeter.java:9: error: non-static method greet() cannot be referenced from a static context
greet();
^
1 errorYou met this message in main is a method too, where the fix was to add static. With objects there is a second fix: make an object, then call the method on it:
ئەم پەیامەت لە mainـیش میتۆدێکە بینی، کە چارەسەرەکەی زیادکردنی static بوو. بە چارەسەرێکی دووەم هەیە: سەرەتا دروست بکە، پاشان لەسەری بانگ بکە:
public class Greeter {
String name = "Hana";
void greet() {
System.out.println("Hello, " + name);
}
public static void main(String[] args) {
Greeter g = new Greeter();
g.greet();
}
}$ java Greeter Hello, Hana
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 9-10
Now
greet()has an object: g, whose name is Hana.ئێستا
greet()هەیە: g، کە ناوی Hanaـیە.
One class per fileهەر کلاسێک لە فایلی خۆیدا
As programs grow, each class gets its own file. A public class must be in a file with exactly its name (The file-name rule), so public class Student goes in Student.java and public class Main in Main.java, side by side in one folder:
کاتێک گەورە دەبن، هەر خۆی وەردەگرێت. public دەبێت لە بێت کە ڕێک ناوی خۆی هەیە (یاسای ناوی فایل)، بۆیە public class Student دەچێتە Student.java و public class Main دەچێتە Main.java، لە تەنیشت یەک لە یەک :
public class Student {
String name;
int mark;
void printReport() {
System.out.println(name + " has " + mark + " marks.");
}
}public class Main {
public static void main(String[] args) {
Student lana = new Student();
lana.name = "Lana";
lana.mark = 88;
lana.printReport();
}
}javac Main.java Student.java
ls
java Main$ javac Main.java Student.java $ ls Main.class Main.java Student.class Student.java $ java Main Lana has 88 marks.
Two shortcuts: javac *.java compiles every file in the folder, and javac Main.java alone also compiles Student.java, because javac looks in the same folder for the classes Main uses (the real ls then shows both class files). Run the class that has main: java Student stops with Error: Main method not found in class Student.
دوو ڕێگەی کورت: javac *.java هەموو کۆمپایل دەکات و javac Main.java بەتەنیاش Student.java کۆمپایل دەکات، چونکە javac لە هەمان بەدوای ئەو دەگەڕێت کە Main بەکاریان دەهێنێت (lsـی ڕاستەقینە پاشان هەردوو class پیشان دەدات). ئەو جێبەجێ بکە کە mainـی تێدایە: java Student بە Error: Main method not found in class Student دەوەستێت.
What new does in memorynew لە بیرگەدا چی دەکات
Student aram = new Student(); does three things. new finds room in memory for a new object and sets its fields to their default values; it runs a constructor (Constructors); and it gives back a , an arrow that says where the object is. The variable aram keeps that reference, not the object itself; Java calls the memory area for objects the heap. A String variable works the same way (A String is an object), while a primitive variable such as int holds the value itself (Every value has a type).
Student aram = new Student(); سێ کار دەکات. new لە شوێن بۆ نوێ دەدۆزێتەوە و دەکات بە ؛ جێبەجێ دەکات (دروستکەرەکان)؛ و دەگەڕێنێتەوە، تیرێک کە دەڵێت لە کوێیە. aram ئەو هەڵدەگرێت، نەک خودی ؛ Java بەو ناوچەیەی کە تێدایە دەڵێت heap. Stringـیش بە هەمان شێوە کار دەکات (String ئۆبجێکتێکە)، بەڵام وەک int خودی هەڵدەگرێت (هەموو نرخێک جۆرێکی هەیە).
What new does in memorynew لە بیرگەدا چی دەکات
Two variables, one objectدوو گۆڕاو، یەک ئۆبجێکت
Because a variable holds only a reference, Student best = aram; copies the arrow, not the object. Now two names lead to one object, and a change through best is seen through aram. == asks whether two references point to the same object, not whether the fields are equal:
چونکە تەنیا هەڵدەگرێت، Student best = aram; تیرەکە کۆپی دەکات، نەک . ئێستا دوو ناو دەچنە سەر یەک و گۆڕانکاری لە ڕێگەی bestـەوە لە ڕێگەی aramـیشەوە دەبینرێت. == دەپرسێت ئایا دوو هەمان نیشان دەدەن، نەک ئایا وەک یەکن:
class Student {
String name;
int mark;
}
public class SameObject {
public static void main(String[] args) {
Student aram = new Student();
aram.name = "Aram";
aram.mark = 85;
Student best = aram; // copies the reference, not the object
best.mark = 99;
System.out.println(aram.name + ": " + aram.mark);
System.out.println(best == aram);
Student other = new Student();
other.name = "Aram";
other.mark = 99;
System.out.println(other == aram);
}
}$ java SameObject Aram: 99 true false
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 12
Copies the reference: both variables now point at the same object.
کۆپی دەکات: ئێستا هەردوو ئاماژە بۆ هەمان دەکەن.
- Lineدێڕی 21
Equal fields, but another object:
false.وەک یەکن، بەڵام ترە:
false.
It is the same == trap as with strings and arrays (Comparing strings, Two names, one array). Comparing objects by their contents needs an equals method that the class writes for itself: see equals(), and Your own class as a key for why hashCode must go with it.
ئەمە هەمان تەڵەی ==ـە کە لە و بینیت (بەراوردکردنی زنجیرەنووسەکان، دوو ناو، یەک ڕیزەک). بەراوردکردنی بەپێی ناوەڕۆکیان equalsـی دەوێت کە بۆ خۆی دەینووسێت: equals() ببینە، هەروەها کلاسی خۆت وەک کلیل بۆ ئەوەی بزانیت بۆچی hashCodeـیش دەبێت لەگەڵیدا بێت.
What new does in memorynew لە بیرگەدا چی دەکات
Passing an object to a methodناردنی ئۆبجێکتێک بۆ میتۆدێک
Java always passes a copy of the value (Java passes a copy), as with arrays (Arrays and methods). For an object, that value is the reference, so the parameter points at the same object and the method can change its fields. Giving the parameter a new object, though, changes only the method's copy of the arrow:
Java هەمیشە کۆپییەکی دەنێرێت (Java کۆپییەک دەنێرێت)، وەک لە (ڕیزەکەکان و میتۆدەکان). بۆ ، ئەو ، بۆیە ئاماژە بۆ هەمان دەکات و دەتوانێت بگۆڕێت. بەڵام دانانی نوێ بۆ تەنیا کۆپییەکەی لە تیرەکە دەگۆڕێت:
class Student {
String name;
int mark;
}
public class GiveBonus {
static void addBonus(Student s, int points) {
s.mark = s.mark + points;
}
static void replace(Student s) {
s = new Student();
s.mark = 0;
}
public static void main(String[] args) {
Student hana = new Student();
hana.name = "Hana";
hana.mark = 80;
addBonus(hana, 5);
System.out.println(hana.name + ": " + hana.mark);
replace(hana);
System.out.println(hana.name + ": " + hana.mark);
}
}$ java GiveBonus Hana: 85 Hana: 85
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 11-13
sgets a copy of hana's arrow;s = new Student()points only that copy elsewhere.sکۆپییەکی تیرەکەی hana وەردەگرێت؛s = new Student()تەنیا ئەو کۆپییە بۆ شوێنێکی تر دەبات.
What new does in memorynew لە بیرگەدا چی دەکات
null: a reference to no objectnull: ئاماژەیەک بۆ هیچ ئۆبجێکتێک
A reference can also be null (): it points to no object. A String field that you never set is null. Calling a method through null, or reading a field through it, stops the program with a NullPointerException, and since Java 15 the message says exactly what was null:
دەتوانێت null () بێت: ئاماژە بۆ هیچ ناکات. String کە هەرگیز نرخت پێ نەداوە nullـە. بانگکردنی لە ڕێگەی null، یان خوێندنەوەی لە ڕێگەیەوە، بە NullPointerException ڕادەگرێت و لە Java 15ـەوە پەیامەکە ڕێک دەڵێت چی null بوو:
class Student {
String name;
int mark;
}
public class NoName {
public static void main(String[] args) {
Student soran = new Student();
soran.mark = 70;
System.out.println("Mark: " + soran.mark);
System.out.println("Name: " + soran.name.toUpperCase());
}
}$ java NoName Mark: 70 Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because "<local1>.name" is null at NoName.main(NoName.java:11)
<local1> means local variable number 1: a plain javac leaves variable names out of the class file. Compile with javac -g and the message names the variable:
<local1> واتە ژمارە 1: javacـی ئاسایی ناوی ناخاتە ناو class. بە javac -g کۆمپایلی بکە و پەیامەکە ناوی دەبات:
javac -g NoName.java
java NoName$ javac -g NoName.java $ java NoName Mark: 70 Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because "soran.name" is null at NoName.main(NoName.java:11)
null: هیچ لە کۆتایی تیرەکەدا نییەCêITWhat new does in memorynew لە بیرگەدا چی دەکات
Objects nobody can reachئەو ئۆبجێکتانەی کەس پێیان ناگات
When no variable refers to an object any more, the program can never use it again. The JVM's finds such objects and frees their memory by itself; in Java you never delete an object (Java's safety). An object becomes unreachable when its last variable gets another object or null, or when the method that held the variable ends. How a garbage collector finds such objects is explained in Memory While a Program Runs.
کاتێک هیچ ئیتر ئاماژە بۆ ناکات، هەرگیز ناتوانێت دووپاتە بەکاری بهێنێتەوە. ئەم جۆرە دەدۆزێتەوە و خۆی ئازاد دەکات؛ لە Javaـدا هەرگیز ناسڕیتەوە (سەلامەتیی Java). کاتێک دەگاتە ئەو حاڵەتە کە دوایین تر یان null وەردەگرێت، یان کاتێک ئەو هەڵگرتبوو کۆتایی دێت. چۆن ئەم دەدۆزێتەوە، لە بیرگە لە کاتی کارکردنی بەرنامەدا ڕوون کراوەتەوە.
Printing an object: toStringچاپکردنی ئۆبجێکتێک: toString
System.out.println(aram) does not print Aram's fields. Without help, Java prints the class name, an @ and the object's hash code in : a number Java gives the object, not its memory address (Java 17 API, Object.toString). The API does not promise the same number in another run or on another computer, so books show other numbers, such as Student@1b6d3586:
System.out.println(aram) Aram چاپ ناکات. بەبێ یارمەتی، Java ناوی ، @ و hash codeـی بە چاپ دەکات: ژمارەیەک کە Java دەیداتە ، نەک ناونیشانی (Java 17 API، Object.toString). API بەڵێن نادات هەمان ژمارە لە جێبەجێکردنێکی تر یان لە کۆمپیوتەرێکی تردا دەربچێت، بۆیە کتێبەکان ژمارەی تر پیشان دەدەن، وەک Student@1b6d3586:
class Student {
String name;
int mark;
}
public class PrintStudent {
public static void main(String[] args) {
Student aram = new Student();
aram.name = "Aram";
aram.mark = 85;
System.out.println(aram);
System.out.println(aram.hashCode());
System.out.println(Integer.toHexString(aram.hashCode()));
}
}$ java PrintStudent Student@6b95977 112810359 6b95977
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 12-13
The same hash code, printed in decimal and in hexadecimal.
هەمان hash code، بە و بە چاپ کراوە.
Give the class a method public String toString() that returns readable text; println and + call it by themselves. @Override asks javac to check that you really replace the toString that every class receives from Object (@Override: let javac check you; one toString for a whole family of classes: toString()):
public String toString() بدە بە کە دەقێکی خوێندراوە دەگەڕێنێتەوە؛ println و + خۆیان بانگی دەکەن. @Override داوا لە javac دەکات بپشکنێت کە بەڕاستی ئەو toStringـە دەگۆڕیت کە هەموو لە Objectـەوە وەریدەگرێت (@Override: با javac بتپشکنێت؛ یەک toString بۆ هەموو خێزانێکی : toString()):
class Student {
String name;
int mark;
@Override
public String toString() {
return name + " (" + mark + ")";
}
}
public class PrintStudent2 {
public static void main(String[] args) {
Student aram = new Student();
aram.name = "Aram";
aram.mark = 85;
System.out.println(aram);
System.out.println("Best student: " + aram);
}
}$ java PrintStudent2 Aram (85) Best student: Aram (85)
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چارەسەر |
|---|---|---|
Calling an instance method from mainبانگکردنی لە mainـەوە | non-static method greet() cannot be referenced from a static context | Make an object first: Greeter g = new Greeter(); g.greet();سەرەتا دروست بکە: Greeter g = new Greeter(); g.greet(); |
| Using an instance field in a static methodبەکارهێنانی لە staticـدا | non-static variable mark cannot be referenced from a static context | Use an object (s.mark), or make the method an instance method بەکار بهێنە (s.mark)، یان بکە بە |
Forgetting new: Student aram; aram.name = "Aram";لەبیرچوونی new: Student aram; aram.name = "Aram"; | variable aram might not have been initialized | Student aram = new Student();Student aram = new Student(); |
A field that is still null: soran.name.toUpperCase() کە هێشتا nullـە: soran.name.toUpperCase() | NullPointerException: Cannot invoke "String.toUpperCase()" because "<local1>.name" is null | Give the field a value first; "Aram".equals(s.name) is safe even when name is nullسەرەتا بدە بە ؛ "Aram".equals(s.name) تەنانەت کاتێک name nullـە سەلامەتە |
A variable that holds null: Student lana = null; lana.mark = 90; کە null هەڵدەگرێت: Student lana = null; lana.mark = 90; | NullPointerException: Cannot assign field "mark" because "<local1>" is null | Make an object with new before you use the variableپێش بەکارهێنانی بە new دروست بکە |
| Two public classes in one fileدوو public لە یەک | class Student is public, should be declared in a file named Student.java | One file per public class, or remove public from the helper classبۆ هەر public ، یان public لە یاریدەدەرەکە لابدە |
Running a class without main: java Studentجێبەجێکردنی بەبێ main: java Student | Error: Main method not found in class Student, please define the main method as: ... | Run the class that has main: java Mainئەو جێبەجێ بکە کە mainـی هەیە: java Main |
| Printing an object without toStringچاپکردنی بەبێ toString | Student@6b95977 | Write public String toString() in the classلە public String toString() بنووسە |
toString() without publictoString() بەبێ public | toString() in Student cannot override toString() in Object ... attempting to assign weaker access privileges; was public | Write it as public String toString()وەک public String toString() بینووسە |
A typo: tostring() instead of toString()هەڵەی نووسین: tostring() لە جیاتی toString() | No error: println still prints Student@6b95977. With @Override: method does not override or implement a method from a supertypeهیچ هەڵەیەک نییە: println هێشتا Student@6b95977 چاپ دەکات. بە @Override: method does not override or implement a method from a supertype | Put @Override above toString(), so javac checks the name@Override لە سەرووی toString() دابنێ، تا javac ناوەکە بپشکنێت |
Comparing two objects with ==بەراوردکردنی دوو بە == | No message: other == aram is simply false, because == compares referencesهیچ پەیامێک نییە: other == aram تەنیا falseـە، چونکە == بەراورد دەکات | Compare the fields, or write an equals method: equals() بەراورد بکە، یان equals بنووسە: equals() |
Practiceڕاهێنان
Write a class Book with the fields title, author and pages, a method printInfo() that prints one line, and a method isLong() that returns true for more than 300 pages. Make two books in main.
Book بنووسە بە title، author و pages، printInfo() کە یەک دێڕ چاپ دەکات و isLong() کە بۆ زیاتر لە 300 لاپەڕە true دەگەڕێنێتەوە. لە mainـدا دوو کتێب دروست بکە.
Hintئاماژە
Start from the Student class of this lesson.
لە Studentـی ئەم وانەیەوە دەست پێ بکە.
Show answerوەڵامەکە پیشان بدە
class Book {
String title;
String author;
int pages;
void printInfo() {
System.out.println(title + " by " + author + ", " + pages + " pages");
}
boolean isLong() {
return pages > 300;
}
}
public class Library {
public static void main(String[] args) {
Book a = new Book();
a.title = "Java Basics";
a.author = "Shilan";
a.pages = 240;
Book b = new Book();
b.title = "Data Structures";
b.author = "Karwan";
b.pages = 410;
a.printInfo();
b.printInfo();
System.out.println("Long books: " + a.isLong() + ", " + b.isLong());
}
}$ java Library Java Basics by Shilan, 240 pages Data Structures by Karwan, 410 pages Long books: false, true
What does this program print? Decide first, then compare with the real run.
ئەم چی چاپ دەکات؟ سەرەتا بڕیار بدە، پاشان لەگەڵ جێبەجێکردنی ڕاستەقینە بەراوردی بکە.
Student a = new Student();
a.mark = 60;
Student b = a;
b.mark = 70;
Student c = new Student();
c.mark = 70;
System.out.println(a.mark + " " + (a == b) + " " + (b == c));Show answerوەڵامەکە پیشان بدە
class Student {
String name;
int mark;
}
public class Predict {
public static void main(String[] args) {
Student a = new Student();
a.mark = 60;
Student b = a;
b.mark = 70;
Student c = new Student();
c.mark = 70;
System.out.println(a.mark + " " + (a == b) + " " + (b == c));
}
}$ java Predict 70 true false
b = a copies the reference, so b.mark = 70 changes the one object: a.mark is 70 and a == b is true. c is another object with the same mark, so b == c is false.
b = a کۆپی دەکات، بۆیە b.mark = 70 تاکە دەگۆڕێت: a.mark 70ـە و a == b trueـە. c ترە بە هەمان نمرە، بۆیە b == c falseـە.
javac rejects this program twice. Read both messages, then fix main without changing switchOn.
javac دوو جار ئەم ڕەت دەکاتەوە. هەردوو پەیامەکە بخوێنەوە، پاشان بەبێ گۆڕینی switchOn main چاک بکە.
public class Lamp {
boolean on;
void switchOn() {
on = true;
}
public static void main(String[] args) {
switchOn();
System.out.println(on);
}
}$ javac Lamp.java
Lamp.java:9: error: non-static method switchOn() cannot be referenced from a static context
switchOn();
^
Lamp.java:10: error: non-static variable on cannot be referenced from a static context
System.out.println(on);
^
2 errorsShow answerوەڵامەکە پیشان بدە
public class Lamp {
boolean on;
void switchOn() {
on = true;
}
public static void main(String[] args) {
Lamp kitchen = new Lamp();
System.out.println(kitchen.on);
kitchen.switchOn();
System.out.println(kitchen.on);
}
}$ java Lamp false true
Both errors have one cause: main is static and has no Lamp object. Make one, then use its method and its field.
هەردوو هەڵەکە یەک هۆیان هەیە: main staticـە و هیچ Lampـی نییە. یەکێک دروست بکە، پاشان و بەکار بهێنە.
Write a class Phone with model and battery (a percentage). use(int percent) lowers the battery but never below 0, charge() sets it to 100 and show() prints both fields. Test it with 40, then use 25, use 30 and charge.
Phone بنووسە بە model و battery (ڕێژەیەکی سەدی). use(int percent) پاترییەکە کەم دەکاتەوە بەڵام هەرگیز لە خوار 0 نا، charge() دەیکاتە 100 و show() هەردوو چاپ دەکات. بە 40 تاقی بکەرەوە، پاشان 25 و 30 بەکار بهێنە و پڕی بکەرەوە.
Show answerوەڵامەکە پیشان بدە
class Phone {
String model;
int battery;
void use(int percent) {
battery = battery - percent;
if (battery < 0) {
battery = 0;
}
}
void charge() {
battery = 100;
}
void show() {
System.out.println(model + ": " + battery + "%");
}
}
public class PhoneTest {
public static void main(String[] args) {
Phone p = new Phone();
p.model = "Rebin's phone";
p.battery = 40;
p.show();
p.use(25);
p.show();
p.use(30);
p.show();
p.charge();
p.show();
}
}$ java PhoneTest Rebin's phone: 40% Rebin's phone: 15% Rebin's phone: 0% Rebin's phone: 100%
For a Student class, decide which members should be static: (a) the student's name, (b) the number of students created so far, (c) a method that turns any mark into a letter grade, (d) a method that prints this student's report, (e) the pass mark that is the same for everyone.
بۆ Student، بڕیار بدە کام ئەندامانە دەبێت static بن: (a) ناوی قوتابی، (b) ژمارەی ئەو قوتابیانەی تا ئێستا دروست کراون، (c) کە هەر نمرەیەک دەکات بە پیتی پلە، (d) کە ڕاپۆرتی ئەم قوتابییە چاپ دەکات، (e) نمرەی دەرچوون کە بۆ هەمووان یەکە.
Show answerوەڵامەکە پیشان بدە
| Memberئەندام | static?static؟ | Whyبۆچی |
|---|---|---|
| (a) | noنا | every student has their own nameهەر قوتابییەک ناوی خۆی هەیە |
| (b) | yesبەڵێ | one count for the whole classیەک ژمارە بۆ هەموو |
| (c) | yesبەڵێ | it needs only its parameter, no objectتەنیا دەوێت، نەک |
| (d) | noنا | it uses this student's fields ئەم قوتابییە بەکار دەهێنێت |
| (e) | yesبەڵێ | one shared value, like passMarkیەک هاوبەش، وەک passMark |
This program compiles but stops when it runs. Explain the message and make the check safe.
ئەم کۆمپایل دەبێت بەڵام لە کاتی جێبەجێکردندا دەوەستێت. پەیامەکە ڕوون بکەرەوە و پشکنینەکە سەلامەت بکە.
class Student {
String name;
int mark;
}
public class FindAramBug {
public static void main(String[] args) {
Student s = new Student();
s.mark = 85;
if (s.name.equals("Aram")) {
System.out.println("Found Aram");
}
}
}$ java FindAramBug Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "<local1>.name" is null at FindAramBug.main(FindAramBug.java:10)
Show answerوەڵامەکە پیشان بدە
class Student {
String name;
int mark;
}
public class FindAram {
public static void main(String[] args) {
Student s = new Student();
s.mark = 85;
if ("Aram".equals(s.name)) {
System.out.println("Found Aram");
} else {
System.out.println("This student has no name yet");
}
}
}$ java FindAram This student has no name yet
s.name was never set, so it is null and s.name.equals(...) has no object to run on. Turn the call around: "Aram".equals(s.name) runs on the literal, which is never null, and simply returns false.
s.name هەرگیز نرخی پێ نەدراوە، بۆیە nullـە و s.name.equals(...) هیچ نییە تا لەسەری جێبەجێ بێت. بانگکردنەکە پێچەوانە بکەرەوە: "Aram".equals(s.name) لەسەر جێبەجێ دەبێت کە هەرگیز null نییە، بۆیە تەنیا false دەگەڕێنێتەوە.
Give a Book with title and pages a toString() so that println(b) prints Java Basics [240 pages].
toString()ـێک بدە بە Bookـێک کە title و pagesـی هەیە، بۆ ئەوەی println(b) Java Basics [240 pages] چاپ بکات.
Show answerوەڵامەکە پیشان بدە
class Book {
String title;
int pages;
@Override
public String toString() {
return title + " [" + pages + " pages]";
}
}
public class Shelf {
public static void main(String[] args) {
Book b = new Book();
b.title = "Java Basics";
b.pages = 240;
System.out.println(b);
System.out.println("On the shelf: " + b);
}
}$ java Shelf Java Basics [240 pages] On the shelf: Java Basics [240 pages]
Summaryکورتە
- A class is the plan; objects are made from it with
new, each with its own values. - Fields hold an object's data and start with default values; read and change them with a dot:
aram.mark. - Instance methods (no
static) work with the fields of the object they are called on:aram.printReport(). - static members belong to the class: one shared copy, used as
Student.passMark; a static method has no object. - A class-type variable holds a reference;
b = ashares one object, and==compares references. nullmeans no object: using it gives aNullPointerException. Unreachable objects are freed by garbage collection.- One public class per file; compile with
javac Main.java Student.java(orjavac *.java) and run the class withmain. - Without
toString()an object prints asStudent@6b95977; writepublic String toString()for readable text.
- نەخشەکەیە؛ بە
newلێی دروست دەکرێن، هەر یەکە و خۆی. - هەڵدەگرن و بە دەست پێ دەکەن؛ بە خاڵ دەیانخوێنیتەوە و دەیانگۆڕیت:
aram.mark. - (بێ
static) لەگەڵ ئەو کار دەکەن کە لەسەری بانگ دەکرێن:aram.printReport(). - ئەندامە staticـەکان هی : یەک کۆپیی هاوبەش، وەک
Student.passMark؛ static هیچ نییە. - جۆری هەڵدەگرێت؛
b = aیەک بەش دەکات و==بەراورد دەکات. nullواتە هیچ نییە: بەکارهێنانیNullPointerExceptionدەدات. بێ ئاماژە بە ئازاد دەکرێن.- بۆ هەر public ؛ بە
javac Main.java Student.java(یانjavac *.java) کۆمپایل بکە و ئەو جێبەجێ بکە کەmainـی هەیە. - بەبێ
toString()وەکStudent@6b95977چاپ دەبێت؛ بۆ دەقی خوێندراوەpublic String toString()بنووسە.
What is the difference between a class and an object?جیاوازیی نێوان کلاس و ئۆبجێکت چییە؟
A class is the description (fields and methods); an object is one thing made from it with new, with its own field values.
وەسفەکەیە ( و )؛ یەک شتە کە بە new لێی دروست دەکرێت و خۆی هەیە.
Why can main not call an instance method directly?بۆچی main ناتوانێت ڕاستەوخۆ بانگی میتۆدێکی ئۆبجێکت بکات؟
main is static, so it has no object. Make an object first and call the method on it.
main staticـە، بۆیە هیچ نییە. سەرەتا دروست بکە و لەسەری بانگ بکە.
What does Student b = a; copy?Student b = a; چی کۆپی دەکات؟
Only the reference: a and b then refer to the same object.
تەنیا : پاشان a و b ئاماژە بۆ هەمان دەکەن.
When do you get a NullPointerException?کەی NullPointerException دەبینیت؟
When you call a method or use a field through a reference that is null, for example a String field that was never set.
کاتێک بانگ دەکەیت یان بەکار دەهێنیت لە ڕێگەی کە nullـە، بۆ نموونە String کە هەرگیز نرخی پێ نەدراوە.
Lesson complete!وانەکە تەواو بوو!
Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.
Key termsزاراوە سەرەکییەکان
Constructors, Modifiers and Encapsulationدروستکەرەکان، دیاریکەرەکان و کەپسوولکردن
Related lecturesوانە پەیوەندیدارەکان
- Constructors, Modifiers and Encapsulationدروستکەرەکان، دیاریکەرەکان و کەپسوولکردن
- Method Overloading and Scopeفرەپێناسەکردنی میتۆد و مەودا
- Strings and String Methodsزنجیرەنووسەکان و میتۆدەکانی String
- Arrays in One and Two Dimensionsڕیزەکەکان لە یەک و دوو ڕەهەنددا
- Inheritance and Polymorphismبۆماوە و فرەشێوەیی
- Dart Classes, Inheritance and Mixinsکلاسەکان، بۆماوە و میکسینەکان لە Dartـدا
- Building Softwareدروستکردنی نەرمەواڵە
- Entity-Relationship Modellingمۆدێلی قەوارە و پەیوەندی
- Python Next to JavaPython لە تەنیشت Javaـەوە
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
- W3Schools: Java OOP
- W3Schools: Java Classes and Objects
- W3Schools: Java Class Attributes
- W3Schools: Java Class Methods
- The Java Tutorials: Creating Objects
- The Java Tutorials: Using Objects (fields, methods, the garbage collector)
- The Java Tutorials: Declaring Member Variables
- The Java Tutorials: Understanding Class Members (static)
- Java SE 17 API: Object (toString, hashCode)
- Java Language Specification (Java SE 17), §4.3.1 Objects and §4.12.5 Initial Values of Variables
- Java Language Specification (Java SE 17), §8.3.1.1 static Fields
- Java Language Specification (Java SE 17), §15.8.3 this and §15.9.4 Run-Time Evaluation of Class Instance Creation Expressions
- JEP 358: Helpful NullPointerExceptions
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.