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ـدا و بە و .
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.
ڕیمۆتی تەلەفزیۆن ئەوە پیشان دەدات کە دەتوانیت چی بکەیت: هەڵکردن، گۆڕینی کەناڵ، بەرزکردنەوەی دەنگ. ئەوەی چۆن دەیکات، بە تیشکی ژێر سوور، چیپ و کۆد، شاراوە دەمێنێتەوە و هەرگیز پێویستت پێی نییە. لە هەمان بیرۆکەیە: کۆدی تر ئەوە دەبینێت کە چی دەکات، واتە ناوی ؛ هەر ئەوە دەشارێتەوە کە چۆن دەیکات.
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).
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() وەک بنووسە: سەرێک بێ جەستە کە بە کۆتایی دێت. ئیتر هەموو تەواو دەبێت جەستەکەی بنووسێت:
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);
}
}
}$ java Shapes Circle: 3.14 Square: 9.0
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ـدا دەستبەجێ دەوەستێت.
$ javac Shapes.java
Shapes.java:33: error: Shape is abstract; cannot be instantiated
Shape s = new Shape();
^
1 errorA 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()، بۆ سەرەوە زیاد بکە:
class Triangle extends Shape {
double base;
double height;
}$ 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 errorThere 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).
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()ـی خۆی جێبەجێ دەبێت:
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();
}
}
}$ java Describe circle: area 3.14 rectangle: area 8.0
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()ـی ڕووت دەکات: لە ناو .
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 گرێبەستەکە واژوو دەکات و پاشان دەبێت هەموو بنووسێت. هەر جۆرێکی خوارەوە لە جیادایە:
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 دەتوانێت بیکات.
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گرێبەستەکە واژوو دەکات.
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() + "%");
}
}$ javac *.java $ java Charging Phone: 70% Laptop: 40%
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 بەکار دەهێنن: بڕوانە بۆماوە، نێوبەستەکان و ترەیتەکان لە کۆرسی وێبدا.
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):
javap Chargeable$ javap Chargeable
Compiled from "Chargeable.java"
interface Chargeable {
public static final int FULL;
public abstract void charge(int);
public abstract int battery();
}Because the methods are public, the class must write public too. Forgetting it is the most common interface mistake:
چونکە publicـن، دەبێت ئەویش public بنووسێت. لەبیرچوونەوەی ئەمە باوترین هەڵەی :
class Phone implements Chargeable {
private int battery = 30;
void charge(int minutes) {
battery = Math.min(FULL, battery + minutes);
}
public int battery() {
return battery;
}
}$ javac *.java
Phone.java:4: error: charge(int) in Phone cannot implement charge(int) in Chargeable
void charge(int minutes) {
^
attempting to assign weaker access privileges; was public
1 errorjavac 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).
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). جۆری ڕێگەش دەدات هەر لە دەرەوە وەربگرێت کە ئەو جێبەجێ دەکات: بڕوانە تێخستنی وابەستەیی.
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).
یەک ، یەک ( زیاتر بە کۆما دوای یەک دێن).
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);
}
}$ javac *.java $ java ChargeAll Phone: 90% Laptop: 50% ElectricScooter: 25%
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4-6
The method knows only the contract, so it works for any Chargeable class, even future ones.
تەنیا گرێبەستەکە دەزانێت، بۆیە بۆ هەر Chargeable کار دەکات، تەنانەت ئەوانەی داهاتووش.
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 لە ڕێگەی هەر یەک لەو دوو جۆرەوە بەکار دێت و هەر جۆرێک تەنیا خۆی پیشان دەدات:
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() + "%");
}
}$ java TwoContracts Photo 1 taken Photo 2 taken Battery: 38%
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.
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 هی خودی و بە ناوەکەیەوە بانگ دەکرێت:
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(...)بانگ دەکرێت.
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.
Laptopdefault دووپاتە پێناسە دەکاتەوە بە یاسای خۆی.
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");
}
}$ javac *.java $ java Defaults Phone needs charge: false Laptop needs charge: true Phone: 75 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 بەکار دەهێنێت.
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 class | Interface |
|---|---|---|
| How a class uses it چۆن بەکاری دەهێنێت | extends: only oneextends: تەنیا یەک | implements: as many as neededimplements: هەر چەندێک پێویست بێت |
| Fields | Any fields, also ones that changeهەر ، ئەوانەش کە دەگۆڕێن | Only constants (public static final)تەنیا (public static final) |
| Constructors | Yesبەڵێ | Noنەخێر |
| Methods | Abstract 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 بێپەیوەندی توانایەکی هاوبەشیان هەیە |
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(...):
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());
}
}$ javac Tickets.java $ ls Bus.class Bus$Seat.class Tickets.class Tickets.java $ java Tickets Hawler - Duhok, seat 12 Hawler - Duhok, seat 13 Sold: 2
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. یارمەتیدەرێکی بچووک لە تەنیشت ئەو تاکە دەهێڵنەوە کە بەکاری دەهێنێت.
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(...)، بەبێ هیچ پاسێک. لە بەرامبەردا ناتوانێت دەرەوە بەکار بهێنێت، چونکە هیچ نییە:
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());
}
}$ java Stops Koya after 50 min
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 8
static: a Stop needs no Bus object.
static:Stopپێویستی بە هیچBusنییە.
$ javac Stops.java
Stops.java:16: error: non-static variable route cannot be referenced from a static context
return name + " on " + route;
^
1 errorInner 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 یارمەتیدەرێکە کە تەنیا دەرەوەکەی دەتوانێت بەکاری بهێنێت؛ هەر تر هەڵە وەردەگرێت:
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);
}
}$ javac Tickets.java
Tickets.java:20: error: Bus.Seat has private access in Bus
Object a = morning.new Seat(12);
^
1 errorInner classes: a class inside a classکلاسە ناوەکییەکان: کلاسێک لە ناو کلاسێکدا
Anonymous classesکلاسە بێناوەکان
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 تەنیا دەتوانێت یەکێک لەوانە هەڵبگرێت و بە == بەراورد دەکرێن:
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);
}
}$ java TeaHouse Order: TEA A glass of tea, coming! false
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1-3
The enum: three constants, separated by commas.
: سێ ، بە کۆما لێک جیا کراونەتەوە.
- Lineدێڕی 9
Enum constants exist once each, so == is safe.
هەر تەنیا یەک جار هەیە، بۆیە
==سەلامەتە.
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 پێش کارکردنی هەموو دەپشکنێت:
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);
}
}$ javac Serve.java
Serve.java:12: error: incompatible types: int cannot be converted to Drink
serve(7);
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error$ 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 errorsThe 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 دەوەستێنێت:
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);
}
}$ java Menu 0 TEA tea 1 COFFEE coffee 2 JUICE juice 3 drinks Found: COFFEE Exception in thread "main" java.lang.IllegalArgumentException: No enum constant Drink.Coffee at java.base/java.lang.Enum.valueOf(Enum.java:273) at Drink.valueOf(Menu.java:1) at Menu.main(Menu.java:14)
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() نابێت: ژمارەکان دەجووڵێن کاتێک کەسێک لە ناوەڕاستدا زیاد دەکات. خودی هەڵبگرە و بەراورد بکە، یان بدە بە (دوو شاشە دواتر).
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 پێت دەڵێت کاتێک یەکێکیان ون بێت:
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);
}
}
}$ java Glasses TEA: a small tea glass, two sugars COFFEE: a cup, no sugar JUICE: a tall glass, already 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 نییە.
$ javac Glasses.java
Glasses.java:8: error: the switch expression does not cover all possible input values
String sweet = switch (d) {
^
1 error

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 دەدات:
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");
}
}
}$ java Bill Total: 3000 IQD TEA costs 500 IQD COFFEE costs 1500 IQD JUICE costs 2000 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ـە، بۆ هەر یەک جار جێبەجێ دەبێت.
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 instantiated | Make an object of a concrete subclass تەواو دروست بکە |
| A subclass without the abstract method بەبێ | Triangle is not abstract and does not override abstract method area() in Shape | Write area(), or make the class abstractarea() بنووسە، یان بکە بە ڕووت |
| An abstract method with a body بە جەستەوە | abstract methods cannot have a body | End 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 Shape | Write abstract class Shapeabstract class Shape بنووسە |
| A class leaves out an interface method لەبیر دەکات | Phone is not abstract and does not override abstract method battery() in Chargeable | Write 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 public | Write publicpublic بنووسە |
new Chargeable()new Chargeable() | Chargeable is abstract; cannot be instantiated | Make an object of a class that implements it ئەو implementsـی دەکات دروست بکە |
| Changing an interface constantگۆڕینی | cannot assign a value to final variable FULL | Constants never change هەرگیز ناگۆڕێن |
| An inner object without an outer object ناوەکی بەبێ دەرەوە | an enclosing instance that contains Bus.Seat is required | morning.new Seat(12)morning.new Seat(12) |
| An outer field inside a static nested class دەرەوە لە ناو static | non-static variable route cannot be referenced from a static context | Pass the value in, or use an inner class بنێرە ناوی، یان بەکار بهێنە |
| A private inner class used outside private لە دەرەوە بەکار هاتووە | Bus.Seat has private access in Bus | Use it only inside its outer classتەنیا لە ناو دەرەوەکەیدا بەکاری بهێنە |
| A value that is not in the enum کە لە نییە | cannot find symbol ... symbol: variable MILKSHAKE location: class Drink | Use an existing constant, or add one to the enum هەبوو بەکار بهێنە، یان یەکێک زیاد بکە بۆ |
new Drink()new Drink() | enum types may not be instantiated | Use the constants: Drink.TEA بەکار بهێنە: Drink.TEA |
| An int where a Drink is expectedintـێک لە شوێنی Drink | incompatible types: int cannot be converted to Drink | Pass 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 constant | Write case TEAcase TEA بنووسە |
| A switch expression that misses a constant کە لەبیر دەکات | the switch expression does not cover all possible input values | Add the missing casecaseـە ونبووەکە زیاد بکە |
Drink.valueOf("Coffee")Drink.valueOf("Coffee") | IllegalArgumentException: No enum constant Drink.Coffee | Use the exact name: "COFFEE"ناوی ڕێک بەکار بهێنە: "COFFEE" |
| A public enum constructor publicـی | modifier public not allowed here | Leave the modifier outدیاریکەرەکە مەنووسە |
Practiceڕاهێنان
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وەڵامەکە پیشان بدە
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);
}
}$ java MoreShapes Total area: 31.57
. Triangle only had to write area(); the loop did not change.
. Triangle تەنیا دەبوو area() بنووسێت؛ نەگۆڕا.
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وەڵامەکە پیشان بدە
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");
}
}$ java Order 3 items: 4000 IQD
An enum can implement an interface, so tea and cake fit in one list: IQD.
دەتوانێت implements بکات، بۆیە چا و کێک لە یەک جێیان دەبێتەوە: دینار.
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وەڵامەکە پیشان بدە
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);
}
}
}$ java Seasons WINTER -> SPRING SPRING: Newroz, 21 March SUMMER: hot and dry AUTUMN: pomegranate harvest WINTER: snow in the mountains
(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 نییە.
javac rejects this lamp twice. Read both messages and fix the class Lamp without changing the interface.
javac دوو جار ئەم چرادانە ڕەت دەکاتەوە. هەردوو پەیامەکە بخوێنەرەوە و Lamp چاک بکە بێ ئەوەی بگۆڕیت.
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());
}
}$ javac LampTest.java
LampTest.java:7: error: Lamp is not abstract and does not override abstract method turnOff() in Switchable
class Lamp implements Switchable {
^
LampTest.java:10: error: turnOn() in Lamp cannot implement turnOn() in Switchable
void turnOn() {
^
attempting to assign weaker access privileges; was public
2 errorsShow answerوەڵامەکە پیشان بدە
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());
}
}$ java LampTest true false
Error 1: turnOff() was missing. Error 2: turnOn() had no public; interface methods are public.
هەڵەی 1: turnOff() نەبوو. هەڵەی 2: turnOn() publicـی نەبوو؛ publicـن.
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: Account | shared fields and code و کۆدی هاوبەش |
| (b) | interface Printable: Printable | unrelated classes, one ability بێپەیوەندی، یەک توانا |
| (c) | abstract class Shape: Shape | shared 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 methodpublic; 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 withvalues(), use bare names incase, 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ـی بدەرێ.
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زاراوە سەرەکییەکان
HashMap and HashSetHashMap و HashSet
Related lecturesوانە پەیوەندیدارەکان
- The switch Statementڕستەی switch
- ArrayList and Wrapper ClassesArrayList و کلاسە پێچەرەوەکان
- Classes and Objects: Attributes and Methodsکلاسەکان و ئۆبجێکتەکان: تایبەتمەندییەکان و میتۆدەکان
- Constructors, Modifiers and Encapsulationدروستکەرەکان، دیاریکەرەکان و کەپسوولکردن
- Sorting, Searching and Lambda Expressionsڕیزکردن، گەڕان و کردارە بێناوەکان
- LinkedList, Iterators, Stacks and QueuesLinkedList، خولپێکەرەکان، ستاکەکان و کیووەکان
- Exceptions: try, catch and finallyهەڵاوێردەکان: try، catch و finally
- Dart Classes, Inheritance and Mixinsکلاسەکان، بۆماوە و میکسینەکان لە Dartـدا
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
- W3Schools: Java Abstraction
- W3Schools: Java Interface
- W3Schools: Java Inner Classes
- W3Schools: Java Anonymous Class
- W3Schools: Java Enums
- dev.java: Abstract Methods and Classes
- dev.java: Interfaces
- dev.java: Nested Classes
- dev.java: Enums
- The Java Tutorials: Abstract Methods and Classes
- The Java Tutorials: Defining an Interface
- The Java Tutorials: Default Methods
- The Java Tutorials: Nested Classes
- The Java Tutorials: Enum Types
- Java SE 17 API: Enum (ordinal, name, valueOf)
- Java Language Specification (Java SE 17), chapter 8: §8.1.1.1 abstract classes, §8.1.3 inner classes, §8.4.3.1 abstract methods, §8.9 enum classes
- Java Language Specification (Java SE 17), chapter 9: §9.3 fields, §9.4 method declarations
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.