- An
abstract classcannot be instantiated and can haveabstractmethods without a body. - An
interfacedefines methods that implementing classes must provide:class Card implements Payment. - A class can implement many interfaces but extend only one class.
- Interfaces can have
defaultmethods with a body.
Java Abstraction & Interfaces
Abstract classes and interfaces.
✍️ 2 exercises in this lessonKey Takeaways: Java Abstraction & Interfaces
Mastering Java Abstraction & Interfaces helps you write clean and reliable Java code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
Java Abstraction & Interfaces Code Example
Javainterface Payment {
double fee();
default String describe() { return getClass().getSimpleName() + " fee: " + fee(); }
}
class Card implements Payment {
public double fee() { return 2.5; }
}
class BankTransfer implements Payment {
public double fee() { return 0; }
}
abstract class Shape {
abstract double area();
}
class Square extends Shape {
double side = 4;
double area() { return side * side; }
}
public class Main {
public static void main(String[] args) {
Payment[] methods = {new Card(), new BankTransfer()};
for (Payment p : methods) System.out.println(p.describe());
System.out.println(new Square().area());
}
}
Output
Card fee: 2.5 BankTransfer fee: 0.0 16.0
Run this example on your own computer. The "Get Started" lesson shows how to set it up.
Java Abstraction & Interfaces Practice Exercises
Check what you learned in “Java Abstraction & Interfaces”.
/ 2 solved
Fill in the blank
Implement an interface.
class Card Payment { }
✓ Correct!
Not quite. Try again.
Multiple choice
How many classes can a Java class extend?
✓ Correct!
Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services