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

Abstract Classes, Interfaces, Inner Classes and Enumsکلاسە ڕووتەکان، نێوبەستەکان، کلاسە ناوەکییەکان و ئینەمەکان

Abstraction in Java: abstract classes with abstract methods that every subclass fills in, and interfaces as contracts (implements, several interfaces, default and static methods, an interface as a type). When to choose which. A first look at inner classes, static nested classes and anonymous classes. Enums as a fixed set of constants: values(), ordinal(), valueOf(), enums in a switch, and enums with fields and a constructor.

لە Javaـدا: بە کە هەموو پڕیان دەکاتەوە و وەک گرێبەست (implements، چەند ، default و static، وەک جۆر). کەی کامیان هەڵبژێریت. سەرەتایەک بۆ ، static و بێناوەکان. وەک کۆمەڵەیەکی جێگیری : values()، ordinal()، valueOf()، لە switchـدا و بە و .

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

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

  • Explain abstraction and write abstract classes with abstract and finished methods.
  • Define interfaces, implement one or several, and use default and static interface methods.
  • Choose between an abstract class and an interface for a design.
  • Read and write inner, static nested and anonymous classes at a first level.
  • Use enums with values(), ordinal(), valueOf(), switch and fields, and fix the javac messages about them.
  • ڕوون بکەیتەوە و بە ڕووت و تەواوەوە بنووسیت.
  • پێناسە بکەیت، یەک یان چەندێکیان implements بکەیت و default و staticـی بەکار بهێنیت.
  • بۆ دیزاینێک لە نێوان و هەڵبژێریت.
  • ، static و بێناوەکان لە ئاستی سەرەتاییدا بخوێنیتەوە و بنووسیت.
  • بە values()، ordinal()، valueOf()، switch و بەکار بهێنیت و پەیامەکانی javac لەبارەیان چاک بکەیتەوە.

Abstraction: what, not howڕووتکردنەوە: چی، نەک چۆن

A TV remote shows what you can do: switch on, change the channel, turn the volume up. How it does it, with infrared light, chips and codes, stays hidden, and you never need to know. Abstraction in programming is the same idea: other code sees what an object can do, the names of its methods, and each class hides how it does it.

ڕیمۆتی تەلەفزیۆن ئەوە پیشان دەدات کە دەتوانیت چی بکەیت: هەڵکردن، گۆڕینی کەناڵ، بەرزکردنەوەی دەنگ. ئەوەی چۆن دەیکات، بە تیشکی ژێر سوور، چیپ و کۆد، شاراوە دەمێنێتەوە و هەرگیز پێویستت پێی نییە. لە هەمان بیرۆکەیە: کۆدی تر ئەوە دەبینێت کە چی دەکات، واتە ناوی ؛ هەر ئەوە دەشارێتەوە کە چۆن دەیکات.

Left, a TV remote with a power button, volume and channel buttons and number keys: what you can do (on/off, volume, channel). Middle, a dashed box with a chip and infrared waves: infrared signals, circuits and codes; how it does it is hidden, and you never need to know it. Right, in Java: what, an abstract method, abstract double area(); how, each subclass: Circle, Math.PI * r * r; Square, side * side; callers only use area(). Bottom: abstract classes and interfaces are how Java shows the what and hides the how.لای چەپ، ڕیمۆتێکی تەلەفزیۆن بە دوگمەی هەڵکردن، دەنگ و کەناڵ و دوگمەی ژمارەکان: ئەوەی دەتوانیت بیکەیت (هەڵکردن، دەنگ، کەناڵ). ناوەڕاست، سندووقێکی پچڕپچڕ بە چیپێک و شەپۆلی ژێر سوور: تیشکی ژێر سوور، سووڕەکان و کۆد؛ چۆن دەیکات شاراوەیە و هەرگیز پێویستت پێی نییە. لای ڕاست، لە Javaـدا: چی، میتۆدێکی ڕووت، abstract double area();؛ چۆن، هەر کلاسی منداڵێک: Circle، Math.PI * r * r؛ Square، side * side؛ بەکارهێنەران تەنیا area() بەکار دەهێنن. لە خوارەوە: کلاسە ڕووتەکان و نێوبەستەکان ڕێگەی Javaـن بۆ پیشاندانی «چی» و شاردنەوەی «چۆن».
Show the what, hide the how«چی» پیشان بدە، «چۆن» بشارەوەCêIT

Java has two tools for abstraction: abstract classes and interfaces. Both list methods that other code may call, and both leave the bodies to the classes below them. You have used the idea already: list.add(...) works without you knowing how an ArrayList keeps its elements (The List interface).

Java دوو ئامرازی بۆ هەیە: و . هەردووکیان ئەو ڕیز دەکەن کە کۆدی تر دەتوانێت بانگیان بکات و هەردووکیان جەستەکان بۆ ئەو جێدەهێڵن کە لە خوارییانەوەن. پێشتر ئەم بیرۆکەیەت بەکار هێناوە: list.add(...) کار دەکات بێ ئەوەی بزانیت ArrayList چۆن هەڵدەگرێت (نێوبەستەی List).

Definitionپێناسە

Showing what something does and hiding how it does it. In object-oriented code, an or an lists the methods that other code may call, and each class fills in its own details.

پیشاندانی ئەوەی شتێک چی دەکات و شاردنەوەی ئەوەی چۆن دەیکات. لە کۆدی ، یان ئەو ڕیز دەکات کە کۆدی تر دەتوانێت بانگیان بکات و هەر وردەکارییەکانی خۆی دەنووسێت.

Abstract classes and abstract methodsکلاسە ڕووتەکان و میتۆدە ڕووتەکان

In the last lesson's exercise Shape had an area() that returned 0 (Shapes and their areas). That means nothing: a shape in general has no area, and new Shape() should not even be possible. Mark the class abstract and write area() as an abstract method: a header with no body, ending in a semicolon. Every concrete subclass must then write the body:

لە ڕاهێنانی وانەی پێشوودا Shape area()ـێکی هەبوو کە 0ـی دەگەڕاندەوە (شێوەکان و ڕووبەرەکانیان). ئەمە هیچ واتایەکی نییە: «شێوەیەکی گشتی» ڕووبەری نییە و نابێت new Shape()ـیش ببێت. بە abstract نیشانە بکە و area() وەک بنووسە: سەرێک بێ جەستە کە بە کۆتایی دێت. ئیتر هەموو تەواو دەبێت جەستەکەی بنووسێت:

Shapes.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
abstract class Shape {
    abstract double area();
}

class Circle extends Shape {
    double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    @Override
    double area() {
        return Math.PI * radius * radius;
    }
}

class Square extends Shape {
    double side;

    Square(double side) {
        this.side = side;
    }

    @Override
    double area() {
        return side * side;
    }
}

public class Shapes {
    public static void main(String[] args) {
        Shape[] shapes = { new Circle(1), new Square(3) };
        for (Shape s : shapes) {
            double a = Math.round(s.area() * 100) / 100.0;
            System.out.println(s.getClass().getSimpleName() + ": " + a);
        }
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1-2

An abstract class with an abstract method: no body, a semicolon.

بە : بێ جەستە، بە .

Lineدێڕی 33-33

Shape is still a fine type for variables and arrays.

Shape هێشتا جۆرێکی باشە بۆ و .

An abstract class cannot be instantiated: the same program with new Shape() in main stops at once.

لێ دروست ناکرێت: هەمان بە new Shape() لە mainـدا دەستبەجێ دەوەستێت.

The same program with new Shape()هەمان بەرنامە بە ⁦new Shape()⁩
$ javac Shapes.java
Shapes.java:33: error: Shape is abstract; cannot be instantiated
        Shape s = new Shape();
                  ^
1 error
The abstract class Shape, drawn with a dashed outline and its name in italics, holds abstract double area();; beside it a dashed shape with a question mark: no shape in particular, area() has no body. Below, Circle with double area() { return Math.PI * r * r; } and Square with double area() { return side * side; } extend it. Three lines: new Shape() is crossed, Shape is abstract; cannot be instantiated; new Circle(1) is ticked, a full class, objects are fine; Shape s = new Square(3); is ticked, a Shape variable may hold any shape.کلاسی ڕووتی Shape، بە دەورەیەکی پچڕپچڕ و ناوێکی لار، abstract double area();ـی تێدایە؛ لە تەنیشتییەوە شێوەیەکی پچڕپچڕ بە نیشانەی پرسیار: هیچ شێوەیەکی دیاریکراو نییە، area() جەستەی نییە. لە خوارەوە Circle بە double area() { return Math.PI * r * r; } و Square بە double area() { return side * side; } لێی extends دەکەن. سێ دێڕ: new Shape() بە ✗، Shape is abstract; cannot be instantiated؛ new Circle(1) بە ✓، کلاسێکی تەواو: ئۆبجێکت دروست دەبێت؛ Shape s = new Square(3); بە ✓، گۆڕاوێکی Shape دەتوانێت هەر شێوەیەک هەڵبگرێت.
An abstract class leaves a gap for its subclasses شوێنێکی چۆڵ بۆ جێدەهێڵێتCêIT
Definitionپێناسە

A that only describes what its subclasses must do and cannot be used to make objects itself. In MVVM an abstract TodoService lists the methods, and TodoServiceRest and TodoServiceMock implement them.

کە تەنیا وەسف دەکات کلاسە لاوەکییەکانی دەبێت چی بکەن و خۆی ناتوانرێت ئۆبجێکتی لێ دروست بکرێت. لە MVVMـدا TodoServiceـی ڕووت میتۆدەکان ڕیز دەکات و TodoServiceRest و TodoServiceMock جێبەجێیان دەکەن.

Abstract classes and abstract methodsکلاسە ڕووتەکان و میتۆدە ڕووتەکان

The rules for abstract classesیاساکانی کلاسە ڕووتەکان

javac makes sure that no object is left with a gap. Add this class, without area(), to the program above:

javac دڵنیا دەبێتەوە کە هیچ بە شوێنێکی چۆڵەوە نامێنێتەوە. ئەم ، بەبێ area()، بۆ سەرەوە زیاد بکە:

JAVA
class Triangle extends Shape {
    double base;
    double height;
}
Outputدەرئەنجام
$ javac Shapes.java
Shapes.java:31: error: Triangle is not abstract and does not override abstract method area() in Shape
class Triangle extends Shape {
^
1 error

There are two ways out: write area() in Triangle, or declare Triangle abstract too (then Triangle makes no objects either). Two more rules: an abstract method has no body (abstract methods cannot have a body), and a class with an abstract method must itself be abstract (Shape is not abstract and does not override abstract method area() in Shape).

دوو ڕێگە هەیە: area() لە Triangleـدا بنووسە، یان Triangleـیش بە abstract ڕابگەیەنە (ئەوکات ئەویش دروست ناکات). دوو یاسای تر: جەستەی نییە (abstract methods cannot have a body) و کە هەبێت دەبێت خۆی ڕووت بێت (Shape is not abstract and does not override abstract method area() in Shape).

The abstract class Shape with abstract double area(); (the gap). Below it, Triangle with double base and double height, and a dashed empty row area() with no body (still empty), crossed. The error: Triangle is not abstract and does not override abstract method area() in Shape. Fix 1, write it: double area() { return base * height / 2; }. Fix 2, make it abstract too: abstract class Triangle; then no Triangle objects.کلاسی ڕووتی Shape بە abstract double area(); (شوێنە چۆڵەکە). لە خوارییەوە Triangle بە double base و double height و ڕیزێکی پچڕپچڕی بەتاڵ area() بێ جەستە (هێشتا بەتاڵە) بە ✗. هەڵەکە: Triangle is not abstract and does not override abstract method area() in Shape. چارەسەری 1، بینووسە: double area() { return base * height / 2; }. چارەسەری 2، ئەویش بکە بە کلاسی ڕووت: abstract class Triangle؛ ئیتر ئۆبجێکتی Triangle نییە.
Every abstract method must be filled inهەموو دەبێت پڕ بکرێتەوەCêIT

Abstract classes and abstract methodsکلاسە ڕووتەکان و میتۆدە ڕووتەکان

An abstract class can hold real codeکلاسی ڕووت دەتوانێت کۆدی ڕاستەقینە هەڵبگرێت

Abstract does not mean empty. An abstract class can have fields, constructors and finished methods, and a finished method may even call an abstract one. Here describe() is written once in Shape and calls area(); for each object, its own class's area() runs:

ڕووت واتای بەتاڵ نییە. دەتوانێت ، و تەواوی هەبێت و تەواو تەنانەت دەتوانێت بانگی بکات. لێرەدا describe() یەک جار لە Shapeـدا نووسراوە و بانگی area() دەکات؛ بۆ هەر ، area()ـی خۆی جێبەجێ دەبێت:

Describe.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
abstract class Shape {
    private final String name;

    Shape(String name) {
        this.name = name;
    }

    abstract double area();                  // every shape must say how

    void describe() {                        // ready-made for every shape
        double a = Math.round(area() * 100) / 100.0;
        System.out.println(name + ": area " + a);
    }
}

class Circle extends Shape {
    private final double radius;

    Circle(double radius) {
        super("circle");
        this.radius = radius;
    }

    @Override
    double area() {
        return Math.PI * radius * radius;
    }
}

class Rectangle extends Shape {
    private final double width;
    private final double height;

    Rectangle(double width, double height) {
        super("rectangle");
        this.width = width;
        this.height = height;
    }

    @Override
    double area() {
        return width * height;
    }
}

public class Describe {
    public static void main(String[] args) {
        Shape[] shapes = { new Circle(1), new Rectangle(2, 4) };
        for (Shape s : shapes) {
            s.describe();
        }
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4-5

An abstract class may have a constructor; subclasses call it with super(...).

دەتوانێت هەبێت؛ بە super(...) بانگی دەکەن.

Lineدێڕی 10-12

A finished method that calls the abstract area(): polymorphism inside the class.

تەواو کە بانگی area()ـی ڕووت دەکات: لە ناو .

The abstract class Shape with the field private final String name, the constructor Shape(String name), the gap abstract double area(); and the ready-made method void describe() { ... area() ... }. Below it Circle with area(): Math.PI * r * r and Rectangle with area(): width * height. The output of s.describe(): circle: area 3.14 and rectangle: area 8.0. Note: describe() is written once, in Shape; inside it area() runs the real object's version.کلاسی ڕووتی Shape بە تایبەتمەندیی private final String name، دروستکەری Shape(String name)، شوێنە چۆڵەکە abstract double area(); و میتۆدە ئامادەکەی void describe() { ... area() ... }. لە خوارییەوە Circle بە area(): Math.PI * r * r و Rectangle بە area(): width * height. دەرخستەی s.describe(): circle: area 3.14 و rectangle: area 8.0. تێبینی: describe() یەک جار لە Shapeـدا نووسراوە؛ لە ناویدا area() وەشانەکەی ئۆبجێکتە ڕاستەقینەکە جێبەجێ دەکات.
Shared code in the abstract class, the gap filled belowکۆدی هاوبەش لە ، شوێنە چۆڵەکە لە خوارەوە پڕ دەکرێتەوەCêIT

Interfaces: a contractنێوبەستەکان: گرێبەست

An interface is a contract: a list of methods that a class promises to have. Think of a wall socket: it fixes the shape of the plug, and every device with the right plug works. A class signs the contract with implements and must then write every method of it. Each type below is in its own file:

گرێبەستێکە: لیستێک لەو کە بەڵێن دەدات هەیبن. بیر لە پریزی دیوار بکەرەوە: شێوەی پلاگەکە دیاری دەکات و هەموو ئامێرێک کە پلاگی گونجاوی هەبێت کار دەکات. بە implements گرێبەستەکە واژوو دەکات و پاشان دەبێت هەموو بنووسێت. هەر جۆرێکی خوارەوە لە جیادایە:

Chargeable.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
interface Chargeable {
    int FULL = 100;                  // a constant

    void charge(int minutes);        // public and abstract
    int battery();
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3-4

No bodies: only what a Chargeable thing can do.

بێ جەستە: تەنیا ئەوەی شتێکی Chargeable دەتوانێت بیکات.

Phone.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Phone implements Chargeable {
    private int battery = 30;

    @Override
    public void charge(int minutes) {
        battery = Math.min(FULL, battery + minutes);       // 1 % per minute
    }

    @Override
    public int battery() {
        return battery;
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

implements: Phone signs the contract.

implements: Phone گرێبەستەکە واژوو دەکات.

Charging.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Charging {
    public static void main(String[] args) {
        Phone phone = new Phone();
        Laptop laptop = new Laptop();
        phone.charge(40);
        laptop.charge(40);
        System.out.println("Phone: " + phone.battery() + "%");
        System.out.println("Laptop: " + laptop.battery() + "%");
    }
}

Laptop.java is written the same way, but its battery starts at 20 % and charge() adds 1 % for every 2 minutes. Compile all the files together with javac *.java. PHP interfaces use the same implements keyword: see Inheritance, Interfaces and Traits in the Web Programming course.

Laptop.java بە هەمان شێوە نووسراوە، بەڵام پاترییەکەی لە ⁦20%⁩ـەوە دەست پێ دەکات و charge() بۆ هەر 2 خولەک ⁦1%⁩ زیاد دەکات. هەموو پێکەوە بە javac *.java کۆمپایل بکە. PHP هەمان implements بەکار دەهێنن: بڕوانە بۆماوە، نێوبەستەکان و ترەیتەکان لە کۆرسی وێبدا.

A wall socket next to the contract «interface» interface Chargeable { void charge(int minutes); int battery(); }: the socket is the contract, which methods, not how they work. Below, plugs that fit, each ticked: Phone, Laptop and ElectricScooter, implements Chargeable, both methods written. A fourth plug, Kettle, has a short pin and is crossed: battery() missing, no fit.پریزێکی دیوار لە تەنیشت گرێبەستی «interface» interface Chargeable { void charge(int minutes); int battery(); }: پریزەکە گرێبەستەکەیە، کام میتۆدانە، نەک چۆن کار دەکەن. لە خوارەوە پلاگی گونجاو، هەر یەکەیان بە ✓: Phone و Laptop و ElectricScooter، implements Chargeable، هەردوو میتۆدەکە نووسراون. پلاگی چوارەم، Kettle، لقێکی کورتی هەیە و ✗ی لەسەرە: battery() نییە، ناگونجێت.
An interface fixes the methods; each class supplies them دیاری دەکات؛ هەر دەیاننووسێتCêIT
Definitionپێناسە

The place where two things meet and work together. A user interface is what a person sees and touches; an is an interface between two programs; a hardware interface, such as USB or SATA, is the connector and rules that join a device to a computer.

ئەو شوێنەیە کە دوو شت تێیدا بەیەک دەگەن و پێکەوە کار دەکەن. ئەوەیە کە مرۆڤ دەیبینێت و دەستی لێ دەدات؛ نێوبەستەیەکە لە نێوان دوو ؛ نێوبەستەی ، وەک USB یان SATA، سەرە پەیوەندی و یاساکانە کە ئامێرێک بە دەبەستن.

Interfaces: a contractنێوبەستەکان: گرێبەست

What javac adds to an interfaceئەوەی javac بۆ نێوبەستەیەک زیاد دەکات

Inside an interface javac adds some words for you: every method without a body is public abstract, and every field is public static final, a constant. javap shows it (Inside a class file):

لە ناو javac هەندێک وشە بۆ تۆ زیاد دەکات: هەموو بێ جەستە public abstractـە و هەموو public static finalـە، واتە . javap پیشانی دەدات (ناوەوەی فایلێکی class):

BASHType in a terminalلە تێرمیناڵدا بینووسە
javap Chargeable

Because the methods are public, the class must write public too. Forgetting it is the most common interface mistake:

چونکە publicـن، دەبێت ئەویش public بنووسێت. لەبیرچوونەوەی ئەمە باوترین هەڵەی :

Phone.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Phone implements Chargeable {
    private int battery = 30;

    void charge(int minutes) {
        battery = Math.min(FULL, battery + minutes);
    }

    public int battery() {
        return battery;
    }
}

javac also refuses a class that leaves a method out (Phone is not abstract and does not override abstract method battery() in Chargeable), new Chargeable() (Chargeable is abstract; cannot be instantiated) and a change to the constant (cannot assign a value to final variable FULL).

javac هەروەها ئەمانە ڕەت دەکاتەوە: کە لەبیر بکات (Phone is not abstract and does not override abstract method battery() in Chargeable)، new Chargeable() (Chargeable is abstract; cannot be instantiated) و گۆڕینی (cannot assign a value to final variable FULL).

Left, what you write: interface Chargeable { int FULL = 100; void charge(int minutes); int battery(); }. Right, what javac compiled, as javap Chargeable shows it: public static final int FULL; public abstract void charge(int); public abstract int battery();, with the added words highlighted. Below: every method of the contract is public, so the class must write public too. void charge(int minutes) { ... } is crossed with the error attempting to assign weaker access privileges; was public; public void charge(int minutes) { ... } is ticked. FULL is a constant: Chargeable.FULL = 90; is refused.لای چەپ، ئەوەی تۆ دەینووسیت: interface Chargeable { int FULL = 100; void charge(int minutes); int battery(); }. لای ڕاست، ئەوەی javac کۆمپایلی کرد، وەک javap Chargeable پیشانی دەدات: public static final int FULL; public abstract void charge(int); public abstract int battery();، کە وشە زیادکراوەکان دیار کراون. لە خوارەوە: هەموو میتۆدێکی گرێبەستەکە publicـە، بۆیە کلاسەکە دەبێت ئەویش public بنووسێت. void charge(int minutes) { ... } بە ✗ و هەڵەی attempting to assign weaker access privileges; was public؛ public void charge(int minutes) { ... } بە ✓. FULL نەگۆڕێکە: Chargeable.FULL = 90; ڕەت دەکرێتەوە.
public abstract methods, public static final fields public abstract، public static finalCêIT

Interfaces: a contractنێوبەستەکان: گرێبەست

An interface is also a typeنێوبەستە جۆریشە

An interface can be the type of a variable, a parameter or a list. ArrayList<Chargeable> holds a phone, a laptop and an electric scooter, although they have nothing else in common. The scooter uses both keywords: it extends Vehicle and implements Chargeable. You have seen an interface type before: List<String> cities = new ArrayList<>(); (The List interface). An interface type also lets a class receive, from outside, any object that implements it: see Dependency Injection.

دەتوانێت جۆری ، یان بێت. ArrayList<Chargeable> مۆبایلێک، و سکووتەرێکی کارەبایی هەڵدەگرێت، هەرچەندە هیچ شتێکی تریان هاوبەش نییە. سکووتەرەکە هەردوو بەکار دەهێنێت: لە Vehicle extends دەکات و Chargeable implements دەکات. پێشتر جۆرێکی بینیوە: List<String> cities = new ArrayList<>(); (نێوبەستەی List). جۆری ڕێگەش دەدات هەر لە دەرەوە وەربگرێت کە ئەو جێبەجێ دەکات: بڕوانە تێخستنی وابەستەیی.

ElectricScooter.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class ElectricScooter extends Vehicle implements Chargeable {
    private int battery = 5;

    ElectricScooter(String plate) {
        super(plate);
    }

    @Override
    public void charge(int minutes) {
        battery = Math.min(FULL, battery + minutes / 3);
    }

    @Override
    public int battery() {
        return battery;
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

One superclass, one interface (more interfaces would follow with commas).

یەک ، یەک ( زیاتر بە کۆما دوای یەک دێن).

ChargeAll.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.ArrayList;

public class ChargeAll {
    static void chargeAll(ArrayList<Chargeable> devices, int minutes) {
        for (Chargeable d : devices) {
            d.charge(minutes);
            System.out.println(d.getClass().getSimpleName() + ": " + d.battery() + "%");
        }
    }

    public static void main(String[] args) {
        ArrayList<Chargeable> devices = new ArrayList<>();
        devices.add(new Phone());
        devices.add(new Laptop());
        devices.add(new ElectricScooter("HW-4321"));
        chargeAll(devices, 60);
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4-6

The method knows only the contract, so it works for any Chargeable class, even future ones.

تەنیا گرێبەستەکە دەزانێت، بۆیە بۆ هەر Chargeable کار دەکات، تەنانەت ئەوانەی داهاتووش.

Vehicle (String plate) and the interface Chargeable (void charge(int minutes), int battery()) at the top. Phone and Laptop implement Chargeable with dashed arrows; ElectricScooter has a solid arrow to Vehicle (extends) and a dashed arrow to Chargeable (implements). Small pictures of a scooter, a phone and a laptop. chargeAll(devices, 60) on an ArrayList<Chargeable> prints Phone: 90%, Laptop: 50%, ElectricScooter: 25%. Notes: a Phone is not a Vehicle, yet all three are Chargeable; a class extends one class and may implement many interfaces.Vehicle (String plate) و نێوبەستەی Chargeable (void charge(int minutes) و int battery()) لە سەرەوە. Phone و Laptop بە تیری پچڕپچڕ Chargeable implements دەکەن؛ ElectricScooter تیرێکی تەواوی بۆ Vehicle هەیە (extends) و تیرێکی پچڕپچڕ بۆ Chargeable (implements). وێنەی بچووکی سکووتەر، مۆبایل و لاپتۆپ. chargeAll(devices, 60) لەسەر ArrayList<Chargeable> چاپ دەکات: Phone: 90% و Laptop: 50% و ElectricScooter: 25%. تێبینییەکان: Phone جۆرێک نییە لە Vehicle، بەڵام هەر سێکیان Chargeableـن؛ کلاسێک لە یەک کلاس extends دەکات و دەتوانێت چەندین نێوبەستە implements بکات.
Unrelated classes, one interface type بێپەیوەندی، یەک جۆری CêIT

Several interfacesچەند نێوبەستەیەک

A class can extend only one class, but it can implement as many interfaces as it needs, separated by commas. A phone can be charged and can take photos: class Phone implements Chargeable, Camera. One Phone object can then be used through either type, and each type shows only its own methods:

تەنیا دەتوانێت لە یەک extends بکات، بەڵام دەتوانێت هەر چەند پێویستی بێت implements بکات، بە کۆما لێک جیا دەکرێنەوە. مۆبایل بارگە دەکرێت و وێنەش دەگرێت: class Phone implements Chargeable, Camera. ئیتر یەک Phone لە ڕێگەی هەر یەک لەو دوو جۆرەوە بەکار دێت و هەر جۆرێک تەنیا خۆی پیشان دەدات:

TwoContracts.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
interface Chargeable {
    int FULL = 100;                  // a constant

    void charge(int minutes);        // public and abstract
    int battery();
}

interface Camera {
    void takePhoto();
}

class Phone implements Chargeable, Camera {
    private int battery = 30;
    private int photos = 0;

    @Override
    public void charge(int minutes) {
        battery = Math.min(FULL, battery + minutes);
    }

    @Override
    public int battery() {
        return battery;
    }

    @Override
    public void takePhoto() {
        photos++;
        battery = battery - 1;
        System.out.println("Photo " + photos + " taken");
    }
}

public class TwoContracts {
    public static void main(String[] args) {
        Phone phone = new Phone();
        Camera cam = phone;            // the same object seen as a Camera
        Chargeable ch = phone;         // ... and as a Chargeable
        cam.takePhoto();
        cam.takePhoto();
        ch.charge(10);
        System.out.println("Battery: " + ch.battery() + "%");
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 12

Two contracts, separated by a comma.

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

Lineدێڕی 37-38

The same object, seen as a Camera and as a Chargeable.

هەمان ، وەک Camera و وەک Chargeable.

Two interfaces at the top: Chargeable with void charge(int minutes) and int battery(), and Camera with void takePhoto(). The class Phone, with int battery and photos and the methods charge(int), battery() and takePhoto(), has dashed implements arrows to both. Below: Chargeable ch = phone; sees charge() and battery(); Camera cam = phone; sees takePhoto(). The output: Photo 1 taken, Photo 2 taken, Battery: 38%.دوو نێوبەستە لە سەرەوە: Chargeable بە void charge(int minutes) و int battery() و Camera بە void takePhoto(). کلاسی Phone، بە int battery و photos و میتۆدەکانی charge(int) و battery() و takePhoto()، تیری پچڕپچڕی implementsـی بۆ هەردووکیان هەیە. لە خوارەوە: Chargeable ch = phone; charge() و battery() دەبینێت؛ Camera cam = phone; takePhoto() دەبینێت. دەرخستە: Photo 1 taken و Photo 2 taken و Battery: 38%.
One class, two contractsیەک ، دوو گرێبەستCêIT

Default methodsمیتۆدەکانی default

Since Java 8 an interface may also contain finished methods. A default method has a body and is inherited by every class that implements the interface, and a class may still override it. Libraries use this to add a method to an old interface without breaking the classes that already implement it. A static method belongs to the interface itself and is called with its name:

لە ⁦Java 8⁩ـەوە دەتوانێت تەواویشی تێدا بێت. default جەستەی هەیە و هەموو ئەو implements دەکەن بە وەریدەگرن و هێشتا دەتوانێت دووپاتە پێناسەی بکاتەوە. ئەمە بەکار دەهێنن بۆ زیادکردنی بۆ کۆن بێ ئەوەی ئەو تێک بدەن کە پێشتر implementsـیان کردووە. static هی خودی و بە ناوەکەیەوە بانگ دەکرێت:

Chargeable.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
interface Chargeable {
    int FULL = 100;

    void charge(int minutes);
    int battery();

    default boolean needsCharge() {          // a ready-made method
        return battery() < 20;
    }

    static int minutesToFull(int battery) {  // belongs to the interface
        return FULL - battery;
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 7-8

A default method: a body that every implementing class receives.

default: جەستەیەک کە هەموو implementsکەر وەریدەگرێت.

Lineدێڕی 11-12

A static method: called as Chargeable.minutesToFull(...).

static: وەک Chargeable.minutesToFull(...) بانگ دەکرێت.

Laptop.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Laptop implements Chargeable {
    private int battery;

    Laptop(int battery) {
        this.battery = battery;
    }

    @Override
    public void charge(int minutes) {
        battery = Math.min(FULL, battery + minutes / 2);
    }

    @Override
    public int battery() {
        return battery;
    }

    @Override
    public boolean needsCharge() {           // a laptop warns earlier
        return battery() < 30;
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 19-20

Laptop overrides the default with its own rule.

Laptop default دووپاتە پێناسە دەکاتەوە بە یاسای خۆی.

Defaults.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Defaults {
    public static void main(String[] args) {
        Phone phone = new Phone(25);
        Laptop laptop = new Laptop(25);
        System.out.println("Phone needs charge: " + phone.needsCharge());
        System.out.println("Laptop needs charge: " + laptop.needsCharge());
        System.out.println("Phone: " + Chargeable.minutesToFull(phone.battery()) + " minutes to full");
    }
}

Phone.java is the Phone of the last screens, with the battery level given to its constructor; it does not write needsCharge(), so it uses the default.

Phone.java هەمان Phoneـی شاشەکانی پێشووە، کە ئاستی پاترییەکە دەدرێت بە ؛ needsCharge() نانووسێت، بۆیە default بەکار دەهێنێت.

The interface Chargeable with void charge(int minutes);, int battery();, default boolean needsCharge() { return battery() < 20; } (it has a body) and static int minutesToFull(int battery) (called on the interface). Phone uses the default needsCharge(); Laptop has @Override needsCharge(): battery() < 30. At battery 25 %: Phone needs charge: false, Laptop needs charge: true. Chargeable.minutesToFull(25) gives 75.نێوبەستەی Chargeable بە void charge(int minutes);، int battery();، default boolean needsCharge() { return battery() < 20; } (جەستەی هەیە) و static int minutesToFull(int battery) (لەسەر نێوبەستە بانگ دەکرێت). Phone needsCharge()ـی default بەکار دەهێنێت؛ Laptop @Override needsCharge(): battery() < 30ـی هەیە. لە پاتریی 25%ـدا: Phone needs charge: false و Laptop needs charge: true. Chargeable.minutesToFull(25) 75 دەدات.
A default method: inherited unless overridden default: بە دێت مەگەر دووپاتە پێناسە بکرێتەوەCêIT

Abstract class or interface?کلاسی ڕووت یان نێوبەستە؟

Both describe methods that subclasses or implementing classes must write, and neither can be created with new. The differences decide which one fits:

هەردووکیان ئەو وەسف دەکەن کە یان implementsکەر دەبێت بیاننووسن و هیچیان بە new دروست ناکرێن. جیاوازییەکان دیاری دەکەن کامیان دەگونجێت:

CompareبەراوردAbstract classInterface
How a class uses it چۆن بەکاری دەهێنێتextends: only oneextends: تەنیا یەکimplements: as many as neededimplements: هەر چەندێک پێویست بێت
FieldsAny fields, also ones that changeهەر ، ئەوانەش کە دەگۆڕێنOnly constants (public static final)تەنیا (public static final)
ConstructorsYesبەڵێNoنەخێر
MethodsAbstract and finished, with any accessڕووت و تەواو، بە هەر دەستڕاگەیشتنێکpublic: abstract, default and static (private helpers since Java 9)public: ڕووت، default و static (یارمەتیدەری private لە ⁦Java 9⁩ـەوە)
Use it whenکەی بەکاری بهێنیتClosely related classes share fields and code نزیک لە یەک و کۆدی هاوبەشیان هەیەUnrelated classes share an ability بێپەیوەندی توانایەکی هاوبەشیان هەیە
Two questions as diamonds. Do the classes share fields or code? Yes: an abstract class, such as Shape with the field name, the finished describe() { ... } and abstract area(); (extends: only one). Do unrelated classes need the same ability? Yes: an interface, such as Chargeable with charge(int minutes) and battery() (implements: many). Both yes? Many classes use both: class ElectricScooter extends Vehicle implements Chargeable.دوو پرسیار وەک چوارگۆشەی لاری بڕیار. ئایا کلاسەکان تایبەتمەندییەکان یان کۆدی هاوبەشیان هەیە؟ بەڵێ: کلاسی ڕووت، وەک Shape بە تایبەتمەندیی name، describe() { ... }ـی تەواو و abstract area(); (extends: تەنیا یەک). ئایا کلاسەکانی بێپەیوەندی هەمان توانایان پێویستە؟ بەڵێ: نێوبەستە، وەک Chargeable بە charge(int minutes) و battery() (implements: چەندین). هەردووکیان بەڵێ؟ زۆر کلاس هەردووکیان بەکار دەهێنن: class ElectricScooter extends Vehicle implements Chargeable.
Shared code: abstract class · shared ability: interfaceکۆدی هاوبەش: · توانای هاوبەش: CêIT

Inner classes: a class inside a classکلاسە ناوەکییەکان: کلاسێک لە ناو کلاسێکدا

A class can be written inside another class. An inner class belongs to one object of its outer class: a Seat belongs to one bus, and its ticket needs that bus's route. Inside Seat, the outer object's fields can be used directly, even private ones. You make an inner object from an outer object, with outer.new Inner(...):

دەتوانرێت لە ناو تردا بنووسرێت. سەر بە یەک دەرەوەکەیەتی: Seat سەر بە یەک پاسە و بلیتەکەی پێویستی بە ڕێگای ئەو پاسەیە. لە ناو Seatـدا دەرەوەکە ڕاستەوخۆ بەکار دێن، تەنانەت ئەوانەی privateـن. ناوەکی لە دەرەوە دروست دەکەیت، بە outer.new Inner(...):

Tickets.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Bus {
    private final String route;
    private int sold = 0;

    Bus(String route) {
        this.route = route;
    }

    class Seat {
        private final int number;

        Seat(int number) {
            this.number = number;
            sold++;                              // the outer bus's field
        }

        String ticket() {
            return route + ", seat " + number;   // even a private field of the bus
        }
    }

    int sold() {
        return sold;
    }
}

public class Tickets {
    public static void main(String[] args) {
        Bus morning = new Bus("Hawler - Duhok");
        Bus.Seat a = morning.new Seat(12);
        Bus.Seat b = morning.new Seat(13);
        System.out.println(a.ticket());
        System.out.println(b.ticket());
        System.out.println("Sold: " + morning.sold());
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 9-10

The inner class, written inside Bus.

، لە ناو Busـدا نووسراوە.

Lineدێڕی 18

Uses the private route of its own bus.

routeـی privateـی پاسەکەی خۆی بەکار دەهێنێت.

Lineدێڕی 30

A Seat of the bus morning.

Seatـێکی پاسی morning.

javac writes the inner class to its own file, Bus$Seat.class. Inner classes keep a small helper next to the only class that uses it.

javac لە جیادا دەنووسێت، Bus$Seat.class. یارمەتیدەرێکی بچووک لە تەنیشت ئەو تاکە دەهێڵنەوە کە بەکاری دەهێنێت.

The outer class Bus, with private final String route and private int sold, contains the inner class Seat, with private final int number and String ticket() { return route + ", seat " + number; }; a dashed arrow shows that Seat may use route, even though it is private. On the right, the object morning, a Bus with route "Hawler - Duhok" and sold 2, and two Seat objects with number 12 and 13, each with a dashed arrow to morning: each Seat knows its own Bus. morning.new Seat(12). javac writes Bus.class and Bus$Seat.class.کلاسە دەرەوەکە، Bus، بە private final String route و private int sold، کلاسی ناوەکیی Seatـی تێدایە بە private final int number و String ticket() { return route + ", seat " + number; }؛ تیرێکی پچڕپچڕ پیشان دەدات کە Seat دەتوانێت route بەکار بهێنێت، هەرچەندە privateـە. لای ڕاست، ئۆبجێکتی morning، Busـێک بە route "Hawler - Duhok" و sold 2، لەگەڵ دوو ئۆبجێکتی Seat بە number 12 و 13، هەر یەکەیان تیرێکی پچڕپچڕی بۆ morning هەیە: هەر Seatـێک Busـەکەی خۆی دەناسێت. morning.new Seat(12). javac دوو فایل دەنووسێت: Bus.class و Bus$Seat.class.
An inner object belongs to one outer object ناوەکی سەر بە یەک دەرەوەیەCêIT
Definitionپێناسە

A written inside another class. It keeps helper code next to the class that uses it and can reach that outer class's private fields; a static nested class needs no outer object, and an anonymous class is a one-off inner class without a name.

کە لە ناو تردا دەنووسرێت. کۆدی یارمەتیدەر لە تەنیشت ئەو بەکاری دەهێنێت دەهێڵێتەوە و دەگاتە privateـی کلاسی دەرەوە؛ ناوەکیی static پێویستی بە دەرەوە نییە و کلاسی بێناو (anonymous class) یەکجارییە کە ناوی نییە.

Inner classes: a class inside a classکلاسە ناوەکییەکان: کلاسێک لە ناو کلاسێکدا

static nested classesکلاسە ناوەکییەکانی static

A nested class marked static does not belong to an outer object. You create it with the outer class's name, new Bus.Stop(...), with no bus at all. In return it cannot use the outer object's fields, because there is none:

کە بە static نیشانە کرابێت سەر بە هیچ دەرەوە نییە. بە ناوی دەرەوەکە دروستی دەکەیت، new Bus.Stop(...)، بەبێ هیچ پاسێک. لە بەرامبەردا ناتوانێت دەرەوە بەکار بهێنێت، چونکە هیچ نییە:

Stops.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Bus {
    private final String route;

    Bus(String route) {
        this.route = route;
    }

    static class Stop {
        private final String name;
        private final int minute;

        Stop(String name, int minute) {
            this.name = name;
            this.minute = minute;
        }

        String info() {
            return name + " after " + minute + " min";
        }
    }
}

public class Stops {
    public static void main(String[] args) {
        Bus.Stop koya = new Bus.Stop("Koya", 50);     // no Bus object needed
        System.out.println(koya.info());
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 8

static: a Stop needs no Bus object.

static: Stop پێویستی بە هیچ Bus نییە.

If Stop's info() uses routeئەگەر ⁦info()⁩ـی Stop route بەکار بهێنێت
$ javac Stops.java
Stops.java:16: error: non-static variable route cannot be referenced from a static context
            return name + " on " + route;
                                   ^
1 error
Left, inner class Seat: the Bus object morning with route "Hawler - Duhok", and a Seat with number 12 whose arrow points to its outer object; Bus.Seat a = morning.new Seat(12); needs a Bus object first and can read route (tick). Right, static nested class Stop: a Stop object with name "Koya" and minute 50 and no Bus object; Bus.Stop koya = new Bus.Stop("Koya", 50); needs no Bus object; using route inside Stop gives non-static variable route cannot be referenced from a static context.لای چەپ، کلاسی ناوەکی، Seat: ئۆبجێکتی Bus، morning، بە route "Hawler - Duhok" و Seatـێک بە number 12 کە تیرەکەی ئاماژە بۆ ئۆبجێکتە دەرەوەکەی دەکات؛ Bus.Seat a = morning.new Seat(12); سەرەتا ئۆبجێکتێکی Busـی پێویستە و دەتوانێت route بخوێنێتەوە (✓). لای ڕاست، کلاسی ناوەکیی static، Stop: ئۆبجێکتێکی Stop بە name "Koya" و minute 50 و هیچ ئۆبجێکتێکی Bus نییە؛ Bus.Stop koya = new Bus.Stop("Koya", 50); ئۆبجێکتێکی Busـی پێویست نییە؛ بەکارهێنانی route لە ناو Stop هەڵەی non-static variable route cannot be referenced from a static context دەدات.
Inner: tied to an outer object · static nested: not tiedناوەکی: بەستراوە بە دەرەوە · static: نەبەستراوەCêIT

Inner classes: a class inside a classکلاسە ناوەکییەکان: کلاسێک لە ناو کلاسێکدا

private inner classesکلاسە ناوەکییەکانی private

Unlike a top-level class, an inner class can be private (or protected). A private inner class is a helper that only its outer class may use; any other class gets an error:

بە پێچەوانەی ئاسایی، دەتوانێت private (یان protected) بێت. private یارمەتیدەرێکە کە تەنیا دەرەوەکەی دەتوانێت بەکاری بهێنێت؛ هەر تر هەڵە وەردەگرێت:

Tickets.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
class Bus {
    private final String route;

    Bus(String route) {
        this.route = route;
    }

    private class Seat {
        private final int number;

        Seat(int number) {
            this.number = number;
        }
    }
}

public class Tickets {
    public static void main(String[] args) {
        Bus morning = new Bus("Hawler - Duhok");
        Object a = morning.new Seat(12);
    }
}

Inner classes: a class inside a classکلاسە ناوەکییەکان: کلاسێک لە ناو کلاسێکدا

Anonymous classesکلاسە بێناوەکان

Two panels. Left, with a name, two steps: class Torch implements Chargeable { ... } and then Chargeable t = new Torch(); javac writes Torch.class, and the class can be used again. Right, with no name, one expression: Chargeable torch = new Chargeable() { ... }; the class has no name, so javac makes one up and writes OneOff$1.class; the class is used once. Bottom: only one abstract method? A lambda expression is even shorter (a later lesson).دوو بەش. لای چەپ، بە ناو، دوو هەنگاو: class Torch implements Chargeable { ... } و پاشان Chargeable t = new Torch(); javac فایلی Torch.class دەنووسێت و کلاسەکە دووپاتە بەکار دێتەوە. لای ڕاست، بێ ناو، یەک دەربڕین: Chargeable torch = new Chargeable() { ... }; کلاسەکە ناوی نییە، بۆیە javac ناوێکی بۆ دادەنێت و فایلی OneOff$1.class دەنووسێت؛ کلاسەکە یەک جار بەکار دێت. لە خوارەوە: تەنیا یەک میتۆدی ڕووت هەیە؟ کرداری بێناو (lambda) لەوەش کورتترە (وانەیەکی داهاتوو).
An anonymous class: written and used in one place بێناو: لە یەک شوێندا دەنووسرێت و بەکار دێت

Enums: a fixed set of valuesئینەمەکان: کۆمەڵەیەکی جێگیری نرخەکان

Some values come from a short, fixed list: the drinks of a tea house, the days of the week, the four seasons. An enum is a type with exactly those values, written in capitals: enum Drink { TEA, COFFEE, JUICE }. A Drink variable can hold only one of them, and enum values are compared with ==:

هەندێک لە لیستێکی کورت و جێگیرەوە دێن: خواردنەوەکانی چایخانەیەک، ڕۆژەکانی هەفتە، چوار وەرزەکە. جۆرێکە کە ڕێک ئەو هەیە، بە پیتی گەورە نووسراون: enum Drink { TEA, COFFEE, JUICE }. Drink تەنیا دەتوانێت یەکێک لەوانە هەڵبگرێت و بە == بەراورد دەکرێن:

TeaHouse.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
enum Drink {
    TEA, COFFEE, JUICE
}

public class TeaHouse {
    public static void main(String[] args) {
        Drink order = Drink.TEA;
        System.out.println("Order: " + order);
        if (order == Drink.TEA) {
            System.out.println("A glass of tea, coming!");
        }
        Drink next = Drink.COFFEE;
        System.out.println(next == order);
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1-3

The enum: three constants, separated by commas.

: سێ ، بە کۆما لێک جیا کراونەتەوە.

Lineدێڕی 9

Enum constants exist once each, so == is safe.

هەر تەنیا یەک جار هەیە، بۆیە == سەلامەتە.

A tea-house menu board titled enum Drink lists TEA, COFFEE and JUICE with a tea glass, a cup and a tall glass, and their ordinals 0, 1 and 2. The variable order, of type Drink, holds TEA and points to it: Drink order = Drink.TEA; (tick). Three lines are crossed: Drink.MILKSHAKE gives cannot find symbol, new Drink() gives enum types may not be instantiated, and serve(7) gives incompatible types: int cannot be converted to Drink. Notes: only these three values exist; javac refuses anything else.تەختەی مێنیوی چایخانەیەک بە سەردێڕی enum Drink، کە TEA و COFFEE و JUICE بە پەرداخێکی چا، کوپێک و پەرداخێکی درێژ و ordinalـی 0 و 1 و 2 ڕیز دەکات. گۆڕاوی order، بە جۆری Drink، TEA هەڵدەگرێت و ئاماژەی بۆ دەکات: Drink order = Drink.TEA; (✓). سێ دێڕ ✗یان لەسەرە: Drink.MILKSHAKE هەڵەی cannot find symbol دەدات، new Drink() هەڵەی enum types may not be instantiated و serve(7) هەڵەی incompatible types: int cannot be converted to Drink. تێبینییەکان: تەنیا ئەم سێ نرخە هەن؛ javac هەر شتێکی تر ڕەت دەکاتەوە.
An enum is a fixed menu مێنیویەکی جێگیرەCêIT
Definitionپێناسە

A type with a fixed list of named , such as enum Level { LOW, MEDIUM, HIGH }. A variable of that type can hold only one of those values, so a mistyped value is caught by the ; enums work well in a switch.

جۆرێکە بە لیستێکی جێگیر لە ناودار، وەک enum Level { LOW, MEDIUM, HIGH }. لەو جۆرە تەنیا دەتوانێت یەکێک لەو نرخانە هەڵبگرێت، بۆیە نرخێکی بە هەڵە نووسراو لەلایەن دەگیرێت؛ لە switchـدا باش کار دەکەن.

Enums: a fixed set of valuesئینەمەکان: کۆمەڵەیەکی جێگیری نرخەکان

Why not numbers or strings?بۆچی ژمارە یان زنجیرەنووسە نا؟

Without an enum, a menu is often coded as numbers (0 for tea) or strings ("tea"). Then nothing stops a 7 or a misspelt "taa". With an enum, javac checks every value before the program runs:

بەبێ ، مێنیو زۆرجار بە ژمارە (0 بۆ چا) یان ("tea") دەنووسرێت. ئەوکات هیچ شتێک ڕێگە لە 7 یان "taa"ـێکی هەڵە نووسراو ناگرێت. بە ، javac پێش کارکردنی هەموو دەپشکنێت:

Serve.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
enum Drink {
    TEA, COFFEE, JUICE
}

public class Serve {
    static void serve(Drink d) {
        System.out.println("Serving " + d);
    }

    public static void main(String[] args) {
        serve(Drink.JUICE);
        serve(7);
    }
}
Two more things javac refusesدوو شتی تر کە javac ڕەتیان دەکاتەوە
$ javac TeaHouse.java
TeaHouse.java:7: error: cannot find symbol
        Drink order = Drink.MILKSHAKE;
                           ^
  symbol:   variable MILKSHAKE
  location: class Drink
TeaHouse.java:8: error: enum types may not be instantiated
        Drink other = new Drink();
                      ^
2 errors

The constants are objects that Java makes for you, one each, when the enum is first used; that is why new Drink() is refused. An enum cannot extend a class either, because every enum already extends java.lang.Enum, but it can implement interfaces.

کە Java بۆ تۆیان دروست دەکات، هەر یەکەیان یەک جار، کاتێک یەکەم جار بەکار دێت؛ هەر بۆیە new Drink() ڕەت دەکرێتەوە. ناتوانێت لە extends بکات، چونکە هەموو پێشتر لە java.lang.Enum extends دەکات، بەڵام دەتوانێت implements بکات.

Enums: a fixed set of valuesئینەمەکان: کۆمەڵەیەکی جێگیری نرخەکان

values(), ordinal() and valueOf()⁦values()⁩ و ⁦ordinal()⁩ و ⁦valueOf()⁩

Every enum gets some ready-made methods automatically. Drink.values() returns an array of all constants in the order they are written, ready for a for-each loop. ordinal() gives a constant's position, starting at 0, and name() its name. Drink.valueOf("COFFEE") turns a string into a constant; the string must match exactly, or an IllegalArgumentException stops the program:

هەموو هەندێک ئامادە بە شێوەی خۆکار وەردەگرێت. Drink.values() لە هەموو دەگەڕێنێتەوە بەو ڕیزەی نووسراون، ئامادە بۆ . ordinal() شوێنی دەدات، لە 0ـەوە و name() ناوەکەی. Drink.valueOf("COFFEE") دەگۆڕێت بۆ ؛ دەبێت ڕێک وەک ناوەکە بێت، ئەگینا IllegalArgumentException دەوەستێنێت:

Menu.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
enum Drink {
    TEA, COFFEE, JUICE
}

public class Menu {
    public static void main(String[] args) {
        for (Drink d : Drink.values()) {
            System.out.println(d.ordinal() + " " + d + " " + d.name().toLowerCase());
        }
        System.out.println(Drink.values().length + " drinks");

        Drink wanted = Drink.valueOf("COFFEE");
        System.out.println("Found: " + wanted);
        Drink typo = Drink.valueOf("Coffee");
        System.out.println("Found: " + typo);
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 7-8

values() in a for-each loop, with each constant's position and name.

values() لە ، لەگەڵ شوێن و ناوی هەر .

Lineدێڕی 14

The name must be exact: "Coffee" is not "COFFEE".

ناوەکە دەبێت ڕێک بێت: ⁦"Coffee"⁩ هەمان ⁦"COFFEE"⁩ نییە.

The Java API documentation says most programmers will have no use for ordinal(): the numbers move when someone adds a constant in the middle. Store and compare the constants themselves, or give the enum a field (two screens on).

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

Drink.values() is an array, in declaration order: TEA, COFFEE, JUICE with 0, 1, 2 under them, equal to ordinal(). The output of d.ordinal() + " " + d + " " + d.name().toLowerCase(): 0 TEA tea, 1 COFFEE coffee, 2 JUICE juice, 3 drinks. Drink.valueOf("COFFEE") is ticked: Found: COFFEE. Drink.valueOf("Coffee") is crossed: IllegalArgumentException: No enum constant Drink.Coffee; valueOf needs the exact name, capitals count. name() gives the constant's name: "TEA".Drink.values() ڕیزەکێکە بە ڕیزبەندیی نووسین: TEA و COFFEE و JUICE کە 0 و 1 و 2 لە خوارییانەوەن و یەکسانن بە ordinal(). دەرخستەی d.ordinal() + " " + d + " " + d.name().toLowerCase(): 0 TEA tea و 1 COFFEE coffee و 2 JUICE juice و 3 drinks. Drink.valueOf("COFFEE") بە ✓: Found: COFFEE. Drink.valueOf("Coffee") بە ✗: IllegalArgumentException: No enum constant Drink.Coffee؛ valueOf ناوی ڕێکی دەوێت، پیتی گەورە گرنگە. name() ناوی نەگۆڕەکە دەدات: "TEA".
values() in order, ordinal() from 0, valueOf() needs the exact name⁦values()⁩ بە ڕیز، ⁦ordinal()⁩ لە 0ـەوە، ⁦valueOf()⁩ ناوی ڕێکی دەوێتCêIT

Enums: a fixed set of valuesئینەمەکان: کۆمەڵەیەکی جێگیری نرخەکان

Enums in a switchئینەمەکان لە switchـدا

Enums and switch work well together (Which values can a switch test?). Write the case labels with the bare constant names, case TEA, not case Drink.TEA; Java 17 refuses the long form (Java 21 and newer accept it, JEP 441, but the bare name stays the usual style). A switch expression (A switch that gives a value) that lists every constant needs no default, and javac tells you when one is missing:

و switch باش پێکەوە کار دەکەن (switch چ نرخێک تاقی دەکاتەوە؟). بە ناوی ڕووتی بنووسە، case TEA، نەک case Drink.TEA؛ ⁦Java 17⁩ شێوە درێژەکە ڕەت دەکاتەوە (⁦Java 21⁩ و نوێتر وەریدەگرن، ⁦JEP 441⁩، بەڵام ناوی ڕووت هەر شێوە باوەکەیە). (switchـێک کە نرخ دەدات) کە هەموو ڕیز بکات پێویستی بە default نییە و javac پێت دەڵێت کاتێک یەکێکیان ون بێت:

Glasses.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
enum Drink {
    TEA, COFFEE, JUICE
}

public class Glasses {
    static String glassFor(Drink d) {
        switch (d) {
            case TEA:
                return "a small tea glass";
            case COFFEE:
                return "a cup";
            default:
                return "a tall glass";
        }
    }

    public static void main(String[] args) {
        for (Drink d : Drink.values()) {
            String sweet = switch (d) {
                case TEA -> "two sugars";
                case COFFEE -> "no sugar";
                case JUICE -> "already sweet";
            };
            System.out.println(d + ": " + glassFor(d) + ", " + sweet);
        }
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 7-13

A switch statement: bare names in the case labels.

: ناوی ڕووت لە .

Lineدێڕی 19-23

A switch expression with all three constants: no default needed.

بە هەر سێ : پێویستی بە default نییە.

A switch expression that forgets JUICEدەربڕینی switchـێک کە JUICE لەبیر دەکات
$ javac Glasses.java
Glasses.java:8: error: the switch expression does not cover all possible input values
        String sweet = switch (d) {
                       ^
1 error
Animation in four steps. The switch expression String sweet = switch (d) { case TEA -> "two sugars"; case COFFEE -> "no sugar"; case JUICE -> "already sweet"; }; with the reminder case TEA, not case Drink.TEA (Java 17). 1: d is Drink.TEA, an arrow lights case TEA, and TEA: a small tea glass, two sugars is printed. 2: d is Drink.COFFEE, case COFFEE gives "no sugar". 3: d is Drink.JUICE, case JUICE gives "already sweet". Last frame: all three cases are ticked; every constant has a case, so no default is needed.
Animation in four steps. The switch expression String sweet = switch (d) { case TEA -> "two sugars"; case COFFEE -> "no sugar"; case JUICE -> "already sweet"; }; with the reminder case TEA, not case Drink.TEA (Java 17). 1: d is Drink.TEA, an arrow lights case TEA, and TEA: a small tea glass, two sugars is printed. 2: d is Drink.COFFEE, case COFFEE gives "no sugar". 3: d is Drink.JUICE, case JUICE gives "already sweet". Last frame: all three cases are ticked; every constant has a case, so no default is needed.
Each constant goes to its own caseهەر دەچێت بۆ caseـی خۆیCêIT

Enums: a fixed set of valuesئینەمەکان: کۆمەڵەیەکی جێگیری نرخەکان

Enums with fields and methodsئینەمەکان بە تایبەتمەندییەکان و میتۆدەکانەوە

An enum is a special class, so it can have fields, a constructor and methods. Give each constant its arguments in brackets, end the list with a semicolon, and write the rest as in a class. The constructor is always private: Java calls it once for each constant, and public Drink(...) gives modifier public not allowed here:

تایبەتە، بۆیە دەتوانێت ، و هەبێت. هەر لە ناو کەوانەدا بدە، لیستەکە بە تەواو بکە و ئەوانی تر وەک لە بنووسە. هەمیشە privateـە: Java بۆ هەر یەک جار بانگی دەکات و public Drink(...) هەڵەی modifier public not allowed here دەدات:

Bill.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
enum Drink {
    TEA(500), COFFEE(1500), JUICE(2000);

    private final int price;            // Iraqi dinars

    Drink(int price) {
        this.price = price;
    }

    int price() {
        return price;
    }
}

public class Bill {
    public static void main(String[] args) {
        Drink[] order = { Drink.TEA, Drink.TEA, Drink.JUICE };
        int total = 0;
        for (Drink d : order) {
            total = total + d.price();
        }
        System.out.println("Total: " + total + " IQD");

        for (Drink d : Drink.values()) {
            System.out.println(d + " costs " + d.price() + " IQD");
        }
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

Each constant with its price; the semicolon ends the list.

هەر بە نرخەکەیەوە؛ لیستەکە تەواو دەکات.

Lineدێڕی 6-7

The constructor: private by default, run once per constant.

: بە شێوەی بنەڕەتی privateـە، بۆ هەر یەک جار جێبەجێ دەبێت.

The code enum Drink { TEA(500), COFFEE(1500), JUICE(2000); private final int price; Drink(int price) { this.price = price; } int price() { return price; } }, with the constant line and the constructor highlighted. Dashed arrows from the constructor lead to three objects: TEA with price 500, COFFEE with price 1500, JUICE with price 2000, each with a drink picture: the constructor runs once for each constant. Below: TEA + TEA + JUICE = 500 + 500 + 2000 = 3000 IQD; the bill reads each price with d.price().کۆدی enum Drink { TEA(500), COFFEE(1500), JUICE(2000); private final int price; Drink(int price) { this.price = price; } int price() { return price; } }، کە دێڕی نەگۆڕەکان و دروستکەرەکە دیار کراون. تیری پچڕپچڕ لە دروستکەرەکەوە دەچن بۆ سێ ئۆبجێکت: TEA بە price 500، COFFEE بە price 1500، JUICE بە price 2000، هەر یەکەیان بە وێنەی خواردنەوەیەک: دروستکەرەکە بۆ هەر نەگۆڕێک یەک جار جێبەجێ دەبێت. لە خوارەوە: TEA + TEA + JUICE = 500 + 500 + 2000 = 3000 IQD؛ پسوولەکە نرخی هەر یەکێک بە d.price() دەخوێنێتەوە.
Each constant carries its own priceهەر نرخی خۆی هەڵدەگرێتCêIT

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چارەسەر
new Shape() for an abstract classnew Shape() بۆ Shape is abstract; cannot be instantiatedMake an object of a concrete subclass تەواو دروست بکە
A subclass without the abstract method بەبێ Triangle is not abstract and does not override abstract method area() in ShapeWrite area(), or make the class abstractarea() بنووسە، یان بکە بە ڕووت
An abstract method with a body بە جەستەوەabstract methods cannot have a bodyEnd the header with a semicolonسەرەکە بە تەواو بکە
An abstract method in a class that is not abstract لە کە ڕووت نییەShape is not abstract and does not override abstract method area() in ShapeWrite abstract class Shapeabstract class Shape بنووسە
A class leaves out an interface method لەبیر دەکاتPhone is not abstract and does not override abstract method battery() in ChargeableWrite every method of the interfaceهەموو بنووسە
An interface method written without public بەبێ public نووسراوەcharge(int) in Phone cannot implement charge(int) in Chargeable; attempting to assign weaker access privileges; was publicWrite publicpublic بنووسە
new Chargeable()new Chargeable()Chargeable is abstract; cannot be instantiatedMake an object of a class that implements it ئەو implementsـی دەکات دروست بکە
Changing an interface constantگۆڕینی cannot assign a value to final variable FULLConstants never change هەرگیز ناگۆڕێن
An inner object without an outer object ناوەکی بەبێ دەرەوەan enclosing instance that contains Bus.Seat is requiredmorning.new Seat(12)morning.new Seat(12)
An outer field inside a static nested class دەرەوە لە ناو staticnon-static variable route cannot be referenced from a static contextPass the value in, or use an inner class بنێرە ناوی، یان بەکار بهێنە
A private inner class used outside private لە دەرەوە بەکار هاتووەBus.Seat has private access in BusUse it only inside its outer classتەنیا لە ناو دەرەوەکەیدا بەکاری بهێنە
A value that is not in the enum کە لە نییەcannot find symbol ... symbol: variable MILKSHAKE location: class DrinkUse an existing constant, or add one to the enum هەبوو بەکار بهێنە، یان یەکێک زیاد بکە بۆ
new Drink()new Drink()enum types may not be instantiatedUse the constants: Drink.TEA بەکار بهێنە: Drink.TEA
An int where a Drink is expectedintـێک لە شوێنی Drinkincompatible types: int cannot be converted to DrinkPass a Drink constant Drink بنێرە
case Drink.TEA (Java 17)case Drink.TEA ⁦(Java 17)⁩an enum switch case label must be the unqualified name of an enumeration constantWrite case TEAcase TEA بنووسە
A switch expression that misses a constant کە لەبیر دەکاتthe switch expression does not cover all possible input valuesAdd the missing casecaseـە ونبووەکە زیاد بکە
Drink.valueOf("Coffee")Drink.valueOf("Coffee")IllegalArgumentException: No enum constant Drink.CoffeeUse the exact name: "COFFEE"ناوی ڕێک بەکار بهێنە: "COFFEE"
A public enum constructor publicـی modifier public not allowed hereLeave the modifier outدیاریکەرەکە مەنووسە

Practiceڕاهێنان

ExerciseڕاهێنانAdd a triangleسێگۆشەیەک زیاد بکە

Add Triangle (a base and a height) to the abstract Shape of this lesson, and print the total area of a 3 × 3 square, a triangle with base 4 and height 5, and a circle of radius 2.

Triangle (بنکە و بەرزی) زیاد بکە بۆ Shapeـی ڕووتی ئەم وانەیە و کۆی ڕووبەری چوارگۆشەیەکی ⁦3 × 3⁩، سێگۆشەیەک بە بنکەی 4 و بەرزیی 5 و بازنەیەک بە نیوەتیرەی 2 چاپ بکە.

Show answerوەڵامەکە پیشان بدە
MoreShapes.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
abstract class Shape {
    abstract double area();
}

class Circle extends Shape {
    double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    @Override
    double area() {
        return Math.PI * radius * radius;
    }
}

class Square extends Shape {
    double side;

    Square(double side) {
        this.side = side;
    }

    @Override
    double area() {
        return side * side;
    }
}

class Triangle extends Shape {
    double base;
    double height;

    Triangle(double base, double height) {
        this.base = base;
        this.height = height;
    }

    @Override
    double area() {
        return base * height / 2;
    }
}

public class MoreShapes {
    public static void main(String[] args) {
        Shape[] shapes = { new Square(3), new Triangle(4, 5), new Circle(2) };
        double total = 0;
        for (Shape s : shapes) {
            total = total + s.area();
        }
        System.out.println("Total area: " + Math.round(total * 100) / 100.0);
    }
}

9+10+12.566…≈31.579 + 10 + 12.566\ldots \approx 31.57. Triangle only had to write area(); the loop did not change.

9+10+12.566…≈31.579 + 10 + 12.566\ldots \approx 31.57. Triangle تەنیا دەبوو area() بنووسێت؛ نەگۆڕا.

ExerciseڕاهێنانA bill with an interfaceپسوولەیەک بە نێوبەستە

Write an interface Priced with int price(). Let the enum Drink (with prices) and a class Cake (1,000 IQD a slice) implement it, and add up an order of a tea, a coffee and two slices of cake from one ArrayList<Priced>.

Priced بە int price() بنووسە. با Drink (بە نرخەکانەوە) و Cake (هەر پارچەیەک ⁦1000⁩ دینار) implementsـی بکەن و داواکارییەکی چایەک، قاوەیەک و دوو پارچە کێک لە یەک ArrayList<Priced>ـدا کۆ بکەرەوە.

Show answerوەڵامەکە پیشان بدە
Order.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.ArrayList;

interface Priced {
    int price();                 // Iraqi dinars
}

enum Drink implements Priced {
    TEA(500), COFFEE(1500), JUICE(2000);

    private final int price;

    Drink(int price) {
        this.price = price;
    }

    @Override
    public int price() {
        return price;
    }
}

class Cake implements Priced {
    private final int slices;

    Cake(int slices) {
        this.slices = slices;
    }

    @Override
    public int price() {
        return slices * 1000;
    }
}

public class Order {
    public static void main(String[] args) {
        ArrayList<Priced> order = new ArrayList<>();
        order.add(Drink.TEA);
        order.add(Drink.COFFEE);
        order.add(new Cake(2));

        int total = 0;
        for (Priced p : order) {
            total = total + p.price();
        }
        System.out.println(order.size() + " items: " + total + " IQD");
    }
}

An enum can implement an interface, so tea and cake fit in one list: 500+1500+2×1000=4000500 + 1500 + 2 \times 1000 = 4000 IQD.

دەتوانێت implements بکات، بۆیە چا و کێک لە یەک جێیان دەبێتەوە: 500+1500+2×1000=4000500 + 1500 + 2 \times 1000 = 4000 دینار.

ExerciseڕاهێنانSeasonsوەرزەکان

Write enum Season { SPRING, SUMMER, AUTUMN, WINTER } with a method next() that returns the next season, WINTER followed by SPRING, using values() and ordinal(). Then print a note for every season with a switch expression.

enum Season { SPRING, SUMMER, AUTUMN, WINTER } بنووسە بە next() کە وەرزی داهاتوو دەگەڕێنێتەوە، دوای WINTER SPRING، بە بەکارهێنانی values() و ordinal(). پاشان بە تێبینییەک بۆ هەموو وەرزێک چاپ بکە.

Hintئاماژە

% gives the remainder of a division.

% دابەشکردن دەدات.

Show answerوەڵامەکە پیشان بدە
Seasons.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
enum Season {
    SPRING, SUMMER, AUTUMN, WINTER;

    Season next() {
        Season[] all = values();
        return all[(ordinal() + 1) % all.length];
    }
}

public class Seasons {
    public static void main(String[] args) {
        Season s = Season.WINTER;
        System.out.println(s + " -> " + s.next());

        for (Season t : Season.values()) {
            String note = switch (t) {
                case SPRING -> "Newroz, 21 March";
                case SUMMER -> "hot and dry";
                case AUTUMN -> "pomegranate harvest";
                case WINTER -> "snow in the mountains";
            };
            System.out.println(t + ": " + note);
        }
    }
}

(ordinal() + 1) % all.length wraps from 3 back to 0. The switch expression lists all four constants, so it needs no default.

(ordinal() + 1) % all.length لە 3ـەوە دەگەڕێتەوە بۆ 0. هەر چوار ڕیز دەکات، بۆیە پێویستی بە default نییە.

ExerciseڕاهێنانFix the lampچرادانەکە چاک بکە

javac rejects this lamp twice. Read both messages and fix the class Lamp without changing the interface.

javac دوو جار ئەم چرادانە ڕەت دەکاتەوە. هەردوو پەیامەکە بخوێنەرەوە و Lamp چاک بکە بێ ئەوەی بگۆڕیت.

LampTest.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
interface Switchable {
    void turnOn();
    void turnOff();
    boolean isOn();
}

class Lamp implements Switchable {
    private boolean on;

    void turnOn() {
        on = true;
    }

    public boolean isOn() {
        return on;
    }
}

public class LampTest {
    public static void main(String[] args) {
        Switchable s = new Lamp();
        s.turnOn();
        System.out.println(s.isOn());
    }
}
Show answerوەڵامەکە پیشان بدە
LampTest.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
interface Switchable {
    void turnOn();
    void turnOff();
    boolean isOn();
}

class Lamp implements Switchable {
    private boolean on;

    @Override
    public void turnOn() {
        on = true;
    }

    @Override
    public void turnOff() {
        on = false;
    }

    @Override
    public boolean isOn() {
        return on;
    }
}

public class LampTest {
    public static void main(String[] args) {
        Switchable s = new Lamp();
        s.turnOn();
        System.out.println(s.isOn());
        s.turnOff();
        System.out.println(s.isOn());
    }
}

Error 1: turnOff() was missing. Error 2: turnOn() had no public; interface methods are public.

هەڵەی 1: turnOff() نەبوو. هەڵەی 2: turnOn() publicـی نەبوو؛ publicـن.

ExerciseڕاهێنانAbstract class or interface?کلاسی ڕووت یان نێوبەستە؟

Choose for each case: (a) savings and current bank accounts that share a balance and a deposit method, (b) reports, photos and tickets that can all be printed, (c) shapes that share a name and a describe() method, (d) very different things that can all be compared with each other.

بۆ هەر حاڵەتێک هەڵبژێرە: ⁦(a)⁩ هەژماری پاشەکەوت و ڕۆژانەی بانک کە باڵانس و پارەدانانیان هاوبەشە، ⁦(b)⁩ ڕاپۆرت، وێنە و بلیت کە هەموویان چاپ دەکرێن، ⁦(c)⁩ شێوەکان کە ناوێک و ⁦describe()⁩ـیان هاوبەشە، ⁦(d)⁩ شتی زۆر جیاواز کە هەموویان دەتوانرێت لەگەڵ یەکتری بەراورد بکرێن.

Show answerوەڵامەکە پیشان بدە
CaseحاڵەتChoiceهەڵبژاردنWhyبۆچی
(a)abstract class Account: Accountshared fields and code و کۆدی هاوبەش
(b)interface Printable: Printableunrelated classes, one ability بێپەیوەندی، یەک توانا
(c)abstract class Shape: Shapeshared name and describe()ناو و ⁦describe()⁩ـی هاوبەش
(d)an interface (Java has Comparable) (Java خۆی Comparableـی هەیە)unrelated classes, one ability بێپەیوەندی، یەک توانا

Comparing and sorting with Comparable comes in Comparable: a natural order inside the class.

بەراوردکردن و بە Comparable لە Comparable: ڕیزی سروشتی لە ناو کلاسەکەدا دێت.

Summaryکورتە

  • Abstraction: show what an object can do, hide how. Java uses abstract classes and interfaces for it.
  • An abstract class cannot be instantiated; its abstract methods have no body, and every concrete subclass writes them. It may also hold fields, constructors and finished methods.
  • An interface is a contract: implements, every method public; fields are constants; a class may implement many interfaces, and an interface is also a type.
  • default methods give interfaces finished methods that classes may override; static interface methods are called on the interface.
  • An inner class belongs to an outer object (outer.new Inner()); a static nested class does not; inner classes can be private.
  • An enum is a fixed set of constants: compare with ==, loop with values(), use bare names in case, and give it fields and a private constructor when each value needs data.
  • : پیشاندانی ئەوەی چی دەکات و شاردنەوەی چۆن. Java بۆ ئەمە و بەکار دەهێنێت.
  • لێ دروست ناکرێت؛ جەستەیان نییە و هەموو تەواو دەیاننووسێت. دەتوانێت ، و تەواویشی هەبێت.
  • گرێبەستێکە: implements، هەموو public؛ ؛ دەتوانێت چەندین implements بکات و جۆریشە.
  • default تەواو دەدەن بە کە دەتوانن دووپاتە پێناسەیان بکەنەوە؛ staticـی لەسەر بانگ دەکرێن.
  • سەر بە دەرەوەیە (outer.new Inner())؛ static نا؛ دەتوانن private بن.
  • کۆمەڵەیەکی جێگیری : بە == بەراورد بکە، بە values() بەسەر هەموویاندا بڕۆ، ناوی ڕووت لە caseـدا بەکار بهێنە و کاتێک هەر پێویستە و privateـی بدەرێ.
Review questionsپرسیارەکانی پێداچوونەوە
Can an abstract class have a constructor?ئایا کلاسی ڕووت دەتوانێت دروستکەری هەبێت؟

Yes. It cannot be called with new, but subclasses call it with super(...).

بەڵێ. بە new بانگ ناکرێت، بەڵام بە ⁦super(...)⁩ بانگی دەکەن.

Why must an interface method be public in the class?بۆچی میتۆدێکی نێوبەستە لە کلاسەکەدا دەبێت public بێت؟

Interface methods are public, and an implementation may not give weaker access.

publicـن و جێبەجێکردنەکەیان ناتوانێت دەستڕاگەیشتنی کەمتر بدات.

What is the difference between an inner class and a static nested class?جیاوازیی کلاسی ناوەکی و کلاسی ناوەکیی static چییە؟

An inner object belongs to an outer object and can use its fields; a static nested object needs no outer object and cannot.

ناوەکی سەر بە دەرەوەیە و دەتوانێت بەکار بهێنێت؛ static پێویستی بە دەرەوە نییە و ناتوانێت.

Why is an enum safer than int codes?بۆچی ئینەم لە کۆدی ژمارەیی سەلامەتترە؟

javac accepts only the listed constants, so a wrong value is a compile error, not a hidden bug.

javac تەنیا ناونووسکراوەکان وەردەگرێت، بۆیە هەڵە دەبێتە ، نەک شاراوە.

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

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

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

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

HashMap and HashSetHashMap و HashSet

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.تەنیا لەسەر ئەم ئامێرە پاشەکەوت دەکرێت.