Mavzu: Dasturlash tilida sinflar. Do’stona funksiyalar. Inkapsulyasiya. Merosxo’rlik. Polimorfizm. Virtual funksiyalar. Ammallar va usullarni qayta ishlash va qayta aniqlash


Download 87.6 Kb.
bet4/4
Sana28.12.2022
Hajmi87.6 Kb.
#1008690
1   2   3   4
Bog'liq
3-mavzu (Inkapsulyasiya. Merosxo\'rlik. Polimorfizm. Virtual funksiyalar)

class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
}
class Dog extends Animal {
public void animalSound() {
System.out.println("The dog says: bow wow");
}
}
class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}

Ichki sinflar

Dasturda sinflarni (sinf ichidagi sinf) joylashtirish ham mumkin. Ichki sinflarning maqsadi bir-biriga tegishli bo'lgan sinflarni guruhlashdan iborat bo'lib, bu sizning kodingizni yanada yaxshi o'qilishi va saqlab turish imkonini beradi.

Ichki sinfga kirish uchun tashqi sinf ob'ekti yaratiladi va keyin ichki sinf ob'ektini yaratiladi:


class OuterClass {
int x = 10;
class InnerClass {
int y = 5;
}
}
public class Main {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}
}
// Outputs 15 (5 + 10)

Ichki sinfdan tashqi sinfga kirish

Ichki sinflarning afzalliklaridan biri shundaki, ular tashqi sinfning atributlari va usullariga kirishlari mumkin:


class OuterClass {
int x = 10;
class InnerClass {
public int myInnerMethod() {
return x;
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass(); System.out.println(myInner.myInnerMethod());
}
} // Outputs 10
Download 87.6 Kb.

Do'stlaringiz bilan baham:
1   2   3   4




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling