Command Palette

Search for a command to run...

Back to the lesson: Topic 5.7 — Interfaces
Core Java · Example 1 of 3

A payment contract with two implementations

An interface is a named list of abilities, a contract, that any class can promise to provide with implements. A class can implement many interfaces, and code written against an interface works with every class that implements it.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Create an interface Shape with double area() and implement it in Circle and Square. Compute the largest area in a List<Shape>.

02

Create interfaces Readable (String read()) and Writable (void write(String s)) and a ReadWrite interface extending both. Implement it with a class that stores the last written string.

03

Make Product(String name, double price) implement Comparable<Product> by price ascending and sort a list.

Explain it without notes

01

What is an interface, and what does a class promise when it implements one?

02

Why can a class implement many interfaces but extend only one class?

03

What does 'program to an interface' mean, and why is it useful?

04

What are the implicit modifiers of methods and fields in an interface?

A payment contract with two implementations
Sign in to run this example in your browser.

Expected output

Shoes via Card: paid
Watch via Card: declined
Book via UPI: paid