Skip to the page

OOP · Write code

Find the four pillars in this code

The interviewer asks

What does this Java program print? Then point to where it shows each of the four pillars of OOP.

abstract class Account {
    private double balance;

    public void deposit(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Amount must be positive");
        }
        balance += amount;
    }

    public double getBalance() { return balance; }

    abstract double interestRate();
}

class SavingsAccount extends Account {
    @Override
    double interestRate() { return 0.04; }
}

class CurrentAccount extends Account {
    @Override
    double interestRate() { return 0.0; }
}

public class Main {
    public static void main(String[] args) {
        Account a = new SavingsAccount();
        a.deposit(1000);
        System.out.println(a.getBalance() + " " + a.interestRate());
    }
}

Then

Follow-ups the interviewer asks next

  1. Why is balance private? What would go wrong if it were public?
  2. Is the call a.interestRate() compile-time or runtime polymorphism?
  3. Can you write new Account()? Why not?
  4. What's the difference between abstraction and encapsulation, in one line each?
  5. Add a fixed-deposit account that doesn't allow deposits after it's opened. What would you change?

The answer

What a strong answer covers

  • It prints 1000.0 0.04 (doubles print with a decimal point).
  • Encapsulation: balance is private, and only deposit can change it, after a check, so no code can set a negative balance.
  • Abstraction: Account says every account has an interest rate without saying how; code holding a doesn't need to know which kind of account it is.
  • Inheritance: SavingsAccount and CurrentAccount reuse deposit and getBalance from Account.
  • Polymorphism: a.interestRate() runs SavingsAccount's version at runtime, though the variable's type is Account (method overriding, dynamic dispatch).
  • An abstract class can't be created with new; only its concrete subclasses can.
  • Abstraction hides how something works and shows what it does; encapsulation keeps data and the code that guards it together and hides the data.
  • Fixed deposit: overriding deposit just to throw an error breaks what callers expect from every Account. Better to model "accepts deposits" separately, or give Account a clear rule such as canDeposit().

The red pen

Common traps

Avoid:treating abstraction and encapsulation as the same thing; saying it prints 0.0 because the variable is an Account; only the textbook animal example, with nothing from the code.

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview