Lesson 29 of 34

Polymorphism, Abstract Classes आणि Interfaces

11 min 35 XP

Abstract class चे objects तयार करता येत नाहीत; child classes ना त्याच्या abstract methods लिहाव्या लागतात. Interface हा करार आहे: तो implement करणाऱ्या class ला त्याच्या सर्व methods लिहाव्या लागतात, आणि एक class अनेक interfaces implement करू शकतो.

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

Shape s = new Circle(...) हे runtime polymorphism आहे: variable चा type Shape आहे पण Circle ची area() चालते. Overriding म्हणजे runtime polymorphism; overloading म्हणजे compile-time.

Challenge

+35 XP

interface Discount { int apply(int price); } लिहा. FlatDiscount 100 कमी करते (0 च्या खाली नाही) आणि PercentDiscount 10% कमी करते (int division); दोन्ही तो implement करतात. main() मध्ये एक price वाचा आणि दोन्ही निकाल print करा. Input: 750 Output: Flat: 650 Percent: 675

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.