Lesson 29 of 34

Polymorphism, Abstract Classes and Interfaces

11 min 35 XP

You can't create objects of an abstract class; child classes must write its abstract methods. An interface is a contract: a class that implements it must write all its methods, and a class can implement many interfaces.

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(...) is runtime polymorphism: the variable's type is Shape but Circle's area() runs. Overriding is runtime polymorphism; overloading is compile-time.

Challenge

+35 XP

Write interface Discount { int apply(int price); }. FlatDiscount takes 100 off (never below 0) and PercentDiscount takes 10% off (int division); both implement it. In main(), read a price and print both results. Input: 750 Output: Flat: 650 Percent: 675

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