Lesson 29 of 34

Polymorphism, Abstract Classes और Interfaces

11 min 35 XP

Abstract class के objects नहीं बना सकते; child classes को उसके abstract methods लिखने होते हैं। Interface एक contract है: उसे 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.