Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีใช้งานอินเทอร์เฟซด้วยคลาสในนามไม่ระบุใน Java

Anonymous inner class คือคลาสที่ไม่มีชื่อ เราจะกำหนดมันโดยตรงที่บรรทัดการสร้างอินสแตนซ์

ตัวอย่าง

ในโปรแกรมต่อไปนี้ เรากำลังนำเมธอด toString() ของอินเทอร์เฟซ TutorialsPoint ไปใช้งานโดยใช้ Anonymous inner class และ พิมพ์ค่าที่คืนมา

interface TutorialsPoint{    public String toString(); } public class Main implements TutorialsPoint {    public static void main(String[] args) {       System.out.print(new TutorialsPoint() {          public String toString() {             return "Welcome to Tutorials Point";          }       });    } }

ผลลัพธ์:

Welcome to Tutorials Point