Menu
CoddyTech

Abstraction and Interfaces Interview Questions

Abstract classes, interfaces, functional and marker interfaces, and the Python equivalents.

10 questions
  1. What is abstraction in OOPs? Give a real example.

    Abstraction is showing what an object does and hiding how, so callers depend on a simple contract. With List<String> names = new ArrayList<>(); you call add and get without caring how items are stored. Interfaces and abstract classes are the tools, and the hidden part can change without breaking callers.

  2. What is the difference between an abstract class and an interface?

    An abstract class is a partly built class that can hold state and constructors; an interface is a contract, and a class can implement many interfaces but extend one class.

    Abstract classInterface
    MethodsAbstract and concreteAbstract; default and static since Java 8, private since Java 9
    FieldsAny instance fieldsOnly public static final constants
    ConstructorsYesNo

    See abstract classes.

  3. When should you use an abstract class instead of an interface?

    Use an interface for a capability that unrelated classes share, and an abstract class when related classes share state and code. A String and an Employee can both be Comparable; a family with common fields and a fixed algorithm fits an abstract class. Default to an interface, which stays open to any class and to lambdas. More in Java interfaces.

  4. Does an abstract class constructor ever run in Java?

    Java
    public class Main {
        public static void main(String[] args) {
            Shape s = new Square(2);
            System.out.print(s.area());
        }
    }
    
    abstract class Shape {
        Shape() { System.out.print("Shape "); }
    
        abstract double area();
    }
    
    class Square extends Shape {
        private final double side;
    
        Square(double side) {
            this.side = side;
            System.out.print("Square ");
        }
    
        @Override
        double area() { return side * side; }
    }

    An abstract class cannot be created with new Shape(), but its constructor runs whenever a subclass is created. new Square(2) calls super() first, which prints Shape , then Square , and area() returns the double 4.0. Use that constructor for the fields every subclass shares.

  5. Can an interface have fields or a constructor?

    No constructor and no instance fields. Variables declared in an interface are implicitly public static final constants:

    interface Limits {
        int MAX_USERS = 100;          // public static final, even without the keywords
        void check(int users);
    }
    

    An interface has no state to initialize, and you never instantiate one directly. Implementing an interface only to use its constants is an anti-pattern; use a final class or an enum.

  6. What is a functional interface?

    A functional interface has exactly one abstract method, so a lambda or method reference can implement it. default and static methods do not count, nor do abstract redeclarations of Object's public methods, so Comparator (it declares equals) is functional.

    Java
    public class Main {
        @FunctionalInterface
        interface Discount {
            double apply(double price);
        }
    
        public static void main(String[] args) {
            Discount none = p -> p;
            Discount festive = p -> p * 0.8;
            Discount flat = p -> Math.max(0, p - 50);
            System.out.println(none.apply(200) + " " + festive.apply(200) + " " + flat.apply(200));
        }
    }

    It prints 200.0 160.0 150.0. More in Java lambdas.

  7. What is a marker interface?

    A marker interface has no methods; implementing it tags the class for an instanceof check. Serializable is the standard example: ObjectOutputStream refuses objects that do not implement it. Annotations are the newer way to attach metadata, but a marker interface is a type, so the compiler can check void save(Serializable s).

  8. How do you create an abstract class in Python?

    Inherit from abc.ABC and mark the required methods with @abstractmethod; Python then refuses to instantiate any class that still has an abstract method.

    Python
    from abc import ABC, abstractmethod
    
    class Shape(ABC):
        @abstractmethod
        def area(self):
            ...
    
    class Square(Shape):
        def __init__(self, side):
            self.side = side
    
        def area(self):
            return self.side ** 2
    
    print(Square(3).area())
    try:
        Shape()
    except TypeError as e:
        print(e)

    It prints 9, then Can't instantiate abstract class Shape with abstract method area (Python 3.11's wording; 3.12 rephrased it). Unlike Java's compile-time check, this one happens when the object is created.

  9. Can an abstract class have no abstract methods?

    Yes. Marking a class abstract only forbids new on it; every method can be concrete. Use it for a base class that makes no sense on its own: HttpServlet is abstract with no abstract methods. The reverse is not allowed: a class with an abstract method must be declared abstract.

    Java
    public class Main {
        public static void main(String[] args) {
            Base b = new Child();      // new Base() would not compile
            System.out.println(b.hello());
        }
    }
    
    abstract class Base {
        String hello() { return "hello from Base"; }
    }
    
    class Child extends Base { }

    It prints hello from Base. An abstract class can still have constructors, static methods and fields.

  10. What are default methods in Java interfaces, and why were they added?

    A default method is an interface method with a body. Java 8 added them so interfaces could grow without breaking every class that implements them: that is how Iterable.forEach and List.sort reached existing collections. A class can override a default, and a method from a class always wins over an interface default.

    Java
    public class Main {
        public static void main(String[] args) {
            Greeter plain = new Plain();
            Greeter custom = new Custom();
            System.out.println(plain.greet("Asha"));
            System.out.println(custom.greet("Asha"));
        }
    }
    
    interface Greeter {
        String name();
    
        default String greet(String who) { return "Hello " + who + ", I am " + name(); }
    }
    
    class Plain implements Greeter {
        public String name() { return "Plain"; }
    }
    
    class Custom implements Greeter {
        public String name() { return "Custom"; }
    
        public String greet(String who) { return "Hi " + who; }
    }

    It prints Hello Asha, I am Plain, then Hi Asha. Interfaces hold no instance state, so a default is written in terms of the abstract methods.

Coddy programming languages illustration

Learn to code with Coddy

Get started