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 calladdandgetwithout caring how items are stored. Interfaces and abstract classes are the tools, and the hidden part can change without breaking callers.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 class Interface Methods Abstract and concrete Abstract; defaultandstaticsince Java 8,privatesince Java 9Fields Any instance fields Only public static finalconstantsConstructors Yes No See abstract classes.
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
Stringand anEmployeecan both beComparable; 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.Does an abstract class constructor ever run in Java?
Javapublic 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)callssuper()first, which printsShape, thenSquare, andarea()returns thedouble4.0. Use that constructor for the fields every subclass shares.Can an interface have fields or a constructor?
No constructor and no instance fields. Variables declared in an interface are implicitly
public static finalconstants: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.
What is a functional interface?
A functional interface has exactly one abstract method, so a lambda or method reference can implement it.
defaultandstaticmethods do not count, nor do abstract redeclarations ofObject's public methods, soComparator(it declaresequals) is functional.Javapublic 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.What is a marker interface?
A marker interface has no methods; implementing it tags the class for an
instanceofcheck.Serializableis the standard example:ObjectOutputStreamrefuses 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 checkvoid save(Serializable s).How do you create an abstract class in Python?
Inherit from
abc.ABCand mark the required methods with@abstractmethod; Python then refuses to instantiate any class that still has an abstract method.Pythonfrom 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, thenCan'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.Can an abstract class have no abstract methods?
Yes. Marking a class
abstractonly forbidsnewon it; every method can be concrete. Use it for a base class that makes no sense on its own:HttpServletis abstract with no abstract methods. The reverse is not allowed: a class with an abstract method must be declaredabstract.Javapublic 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,staticmethods and fields.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.forEachandList.sortreached existing collections. A class can override a default, and a method from a class always wins over an interface default.Javapublic 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, thenHi Asha. Interfaces hold no instance state, so a default is written in terms of the abstract methods.
Abstraction and Interfaces Interview Questions
Abstract classes, interfaces, functional and marker interfaces, and the Python equivalents.