Interfaces & abstract classes

Computer Science · Java

Question 1 of 10

0

    Which file extension do Java source files use?

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Interfaces & abstract classes explained

    An interface and an abstract class both describe what a class must provide without always implementing it all. An interface lists methods that an implementing class promises to write. An abstract class can hold shared fields and finished methods as well as abstract methods that subclasses must complete. A class can implement many interfaces but extend only one class.

    An interface is declared with the interface keyword, and a class uses implements to promise to write every method the interface lists. Since Java 8, an interface can also provide default methods with bodies. Its fields are always public, static and final constants. An abstract class is declared with abstract and cannot be created with new, and a subclass uses extends and must implement every inherited abstract method unless it is also abstract. Use an interface for a capability shared by unrelated classes, and an abstract class when related classes share state or code.

    interface Shape {
        double area();
    }
    
    class Square implements Shape {
        double side;
    
        Square(double side) {
            this.side = side;
        }
    
        public double area() {
            return side * side;
        }
    }
    
    Shape s = new Square(3.0);
    System.out.println(s.area());
    

    Worked example

    Trace the code above.

    1. Square implements Shape, so it must provide area().
    2. new Square(3.0) sets side to 3.0.
    3. s.area() returns 3.0×3.0=9.03.0 \times 3.0 = 9.0, because the call runs Square's version of the method.
    4. The statement Shape s = new Shape(); would not compile, because an interface cannot be created directly.

    What you will practise

    104 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.

    Example questions

    • An interface in Java:
    • A class implements an interface with:
    • An abstract class:
    • A class extends another with:
    • A class can implement:
    • Which keyword marks a method as having no implementation in an abstract class?
    • How many superclasses can a Java class extend directly?
    • Methods declared in an interface are, by default, which access level?

    …and 96 more.