Java-da abstraktsiyaga erishishning yana bir yo'li interfeyslardir.
An interfacebutunlay " mavhum sinf " bo'lib, u bo'sh jismlar bilan bog'liq usullarni guruhlash uchun ishlatiladi:
Misol
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}
Interfeys usullariga kirish uchun interfeys kalit so'zi implements (o'rniga extends) bilan boshqa sinf tomonidan "amalga oshirilgan" bo'lishi kerak (meroslangan kabi). Interfeys usulining asosiy qismi "amalga oshirish" klassi tomonidan taqdim etiladi:
Misol
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Interfeyslar haqida eslatmalar:
Mavhum sinflar singari , interfeyslarni ob'ektlar yaratish uchun ishlatib bo'lmaydi (yuqoridagi misolda MyMainClassda "Hayvon" ob'ektini yaratish mumkin emas)
Interfeys usullari tanasiga ega emas - tanasi "amalga oshirish" klassi tomonidan taqdim etiladi
Interfeys usullari sukut bo'yicha abstractva public
Interfeys atributlari sukut bo'yicha public, staticvafinal
Interfeys konstruktorni o'z ichiga olmaydi (chunki uni ob'ektlar yaratish uchun ishlatib bo'lmaydi)
Nima uchun va qachon interfeyslardan foydalanish kerak?
1) Xavfsizlikka erishish uchun - ba'zi tafsilotlarni yashirish va faqat ob'ektning (interfeysning) muhim tafsilotlarini ko'rsatish.
2) Java "bir nechta merosni" qo'llab-quvvatlamaydi (sinf faqat bitta supersinfdan meros bo'lishi mumkin). Biroq, bunga interfeyslar yordamida erishish mumkin, chunki sinf bir nechta interfeyslarni amalga oshirishi mumkin . Eslatma: Bir nechta interfeyslarni amalga oshirish uchun ularni vergul bilan ajrating (quyidagi misolga qarang).