These are the notes for CS Fundamentals for Placements, episode 13, the second of three episodes on object-oriented programming (OOP). Last episode we built an Account class. This time the bank wants more kinds of accounts, and that one request makes you invent: inheritance (base/parent and derived/child classes, the five types of inheritance), the super keyword and constructor chaining, method overloading and operator overloading, method overriding, compile-time vs runtime polymorphism, static vs dynamic binding, upcasting and downcasting, virtual functions, the vtable and vptr, abstract classes and pure virtual functions, interfaces, the diamond problem and virtual inheritance, and final/sealed classes and methods. Every term is explained in plain words the first time it appears, and there is a full glossary at the end. All outputs and error messages below are real: the Java programs were compiled and run with javac/java 21, the C++ programs with g++ 13.3, on 29 October 2026.
A quick refresher from episode 12: a class is a blueprint (which data and actions every object has); an object (an instance) is one real thing made from it with new; fields are the variables inside an object (its state) and methods are its functions (its behaviour); a constructor is the special method that runs when an object is created; this means "the current object"; private hides a member from code outside its class. A compile error is reported by the compiler before the program runs; a runtime exception happens while it runs.
The eight problems
| Problem | What it teaches |
|---|---|
| Copy-pasted classes drift apart | Inheritance, extends, parent/base/superclass, child/derived/subclass, is-a, five types of inheritance |
| The parent part isn't built | super(...), super.x, constructor chaining and the order constructors run |
| One name, many inputs | Method overloading; operator overloading in C++ |
| Month end differs per account | Method overriding, @Override, polymorphism, upcasting, compile-time vs runtime polymorphism, binding |
| Using child features again | Downcasting, ClassCastException, instanceof |
| How is the method picked? | C++ static binding, virtual, vtable, vptr, the cost in bytes |
| An account of no type | Abstract classes and methods, pure virtual functions |
| Two parents; rules that must hold | Multiple inheritance, diamond problem, virtual inheritance, interfaces, final, sealed |
Problem 1: copy-pasted classes drift apart (inheritance)
The bank launches savings accounts: an account plus an interest rate. The fastest way is to copy Account, rename it and add a field. Weeks later someone fixes a bug in deposit (it accepted negative amounts) but only in the original:
class Account {
String name;
int balance;
void deposit(int amount) {
if (amount <= 0) { System.out.println("Rejected"); return; }
balance += amount; // bug fixed here...
}
}
class SavingsAccount { // copy-pasted from Account
String name;
int balance;
double rate = 0.04;
void deposit(int amount) {
balance += amount; // ...but not here
}
}
public class Main {
public static void main(String[] args) {
Account a = new Account();
SavingsAccount s = new SavingsAccount();
a.deposit(-500);
s.deposit(-500);
System.out.println(a.balance + " " + s.balance);
}
}
Output:
Rejected
0 -500
The fixed class rejects −500; the copy goes to −500. Copy-paste means every bug lives twice, and every fix must be remembered twice.
Real-life example: a family business. A father builds a shop once: stock, register, rules. His son receives the shop as it is and adds a new counter. A new rule applies to both shops instantly, because there's only one copy of it.
- The class others build on is the parent class, also called the base class or superclass.
- The class that builds on it is the child class, also called the derived class or subclass.
- The child automatically receives every field and method of the parent and adds only what is new. That is inheritance. In Java the keyword is
extends; in C++ it isclass Child : public Parent.
class Account {
String name;
int balance;
void deposit(int amount) {
if (amount <= 0) { System.out.println("Rejected"); return; }
balance += amount;
}
}
class SavingsAccount extends Account { // is-a Account
double rate = 0.04; // only what's new
}
public class Main {
public static void main(String[] args) {
SavingsAccount s = new SavingsAccount();
s.deposit(-500);
s.deposit(1000);
System.out.println(s.balance + " at " + s.rate);
}
}
Output:
Rejected
1000 at 0.04
SavingsAccount never wrote deposit or balance, yet it has both, with the bug fix included. The is-a test: say "a savings account is an account". If the sentence is true, inheritance fits. If it sounds wrong ("a car is an engine"), it doesn't (episode 14).
The five types of inheritance
| Type | Shape | Example |
|---|---|---|
| Single | one parent → one child | Account → SavingsAccount |
| Multilevel | a chain: grandparent → parent → child | Account → SavingsAccount → KidsSavingsAccount |
| Hierarchical | one parent → many children | SavingsAccount and CurrentAccount both extend Account |
| Multiple | one child ← two or more parents | C++ only: class StaffCustomer : public Customer, public Employee |
| Hybrid | a mix of the above | multilevel + multiple together |
Java classes support single, multilevel and hierarchical inheritance. Multiple (and therefore hybrid) inheritance of classes is not allowed in Java; Java gets the same benefit through interfaces (problem 8). C++ allows all five.
Problem 2: building the parent part (super and constructor chaining)
Account has a constructor that needs a name and a balance. The child's constructor only sets the rate:
class Account {
String name;
int balance;
Account(String name, int balance) {
this.name = name;
this.balance = balance;
}
}
class SavingsAccount extends Account {
double rate;
SavingsAccount(String name, int balance, double rate) {
this.rate = rate;
}
}
public class Main {
public static void main(String[] args) {
SavingsAccount s = new SavingsAccount("Riya", 5000, 0.04);
System.out.println(s.name);
}
}
Output:
Main.java:12: error: constructor Account in class Account cannot be applied to given types;
SavingsAccount(String name, int balance, double rate) {
^
required: String,int
found: no arguments
reason: actual and formal argument lists differ in length
1 error
Why: a child object contains a parent part, and the parent part must be built first by a parent constructor. We didn't say which one, so Java tried to call the parent's no-argument constructor, Account(), which doesn't exist.
The fix: super.
super(arguments)calls the parent's constructor. It must be the first statement of the child's constructor.super.nameorsuper.method()reaches the parent's version of a field or method (useful when the child has overridden it).- If you don't write
super(...), Java insertssuper()(no arguments) for you, which is exactly what failed above.
class Account {
String name;
int balance;
Account(String name, int balance) {
System.out.println("1. Account part built");
this.name = name;
this.balance = balance;
}
}
class SavingsAccount extends Account {
double rate;
SavingsAccount(String name, int balance, double rate) {
super(name, balance); // parent's constructor first
System.out.println("2. Savings part built");
this.rate = rate;
}
}
public class Main {
public static void main(String[] args) {
SavingsAccount s = new SavingsAccount("Riya", 5000, 0.04);
System.out.println(s.name + ": " + s.balance);
}
}
Output:
1. Account part built
2. Savings part built
Riya: 5000
The parent's constructor always runs first, then the child's. Each constructor calling the one above it, all the way up to Object (the root of every Java class), is constructor chaining. In episode 12 you also saw chaining within one class with this(...). Rule: a constructor's first line can be this(...) or super(...), never both.
In C++ the parent part is built in the initializer list: Savings(string n, int b) : Account(n, b) { }.
Problem 3: one name, many inputs (overloading)
Some deposits come with a note ("salary"). Instead of inventing depositWithNote, Java lets two methods share a name as long as their parameter lists differ (number, types or order of parameters):
class Account {
String name;
int balance;
Account(String name, int balance) {
this.name = name;
this.balance = balance;
}
void deposit(int amount) { // version 1
balance += amount;
}
void deposit(int amount, String note) { // version 2
balance += amount;
System.out.println("Deposited " + amount + " (" + note + ")");
}
}
public class Main {
public static void main(String[] args) {
Account a = new Account("Riya", 5000);
a.deposit(500);
a.deposit(1000, "salary");
System.out.println("Balance: " + a.balance);
}
}
Output:
Deposited 1000 (salary)
Balance: 6500
This is method overloading: same name, different parameters, usually in the same class. The compiler picks the version by looking at the arguments, while compiling. Rules:
| Allowed to differ | Not enough on its own |
|---|---|
| number of parameters | return type only (int f() vs void f() is an error) |
| types of parameters | parameter names only |
| order of parameter types | access modifier only |
Constructors can be overloaded too (episode 12).
Operator overloading (C++)
Operator overloading means giving an operator such as + a meaning for your own type. C++ allows it by writing a method named operator+:
#include <iostream>
using namespace std;
class Money {
public:
int rupees;
Money(int r) : rupees(r) { }
Money operator+(const Money& other) { // teach + about Money
return Money(rupees + other.rupees);
}
};
int main() {
Money salary(30000), bonus(5000);
Money total = salary + bonus; // reads like maths
cout << "Total: " << total.rupees << endl;
}
Output:
Total: 35000
Java does not allow operator overloading. The only exception is built into the language: + joins Strings.
Problem 4: month end differs per account (overriding and polymorphism)
At month end the bank runs one job on every account: a plain account does nothing, a savings account earns 1% interest, a current account (the kind businesses use for many transactions) pays a ₹50 fee.
Real-life example: the school bell. It rings once, the same signal for everyone, and each class reacts its own way: lunch, lab, home. The bell doesn't know who hears it.
- A child class writing its own version of a parent method, with the same name, parameters and return type, is method overriding.
@Overrideis an annotation (a label for the compiler) that asks javac to check that you really are overriding a parent method. Misspell the name and you get an error instead of a silent new method.- One call doing different things depending on the real object is polymorphism (Greek: poly = many, morph = form).
class Account {
String name; int balance = 1000;
Account(String n) { name = n; }
void monthEnd() { } // plain: nothing
}
class SavingsAccount extends Account {
SavingsAccount(String n) { super(n); }
@Override
void monthEnd() { balance += balance / 100; } // +1%
}
class CurrentAccount extends Account {
CurrentAccount(String n) { super(n); }
@Override
void monthEnd() { balance -= 50; } // Rs 50 fee
}
public class Main {
public static void main(String[] args) {
Account[] all = { new Account("Aman"),
new SavingsAccount("Riya"), new CurrentAccount("Kabir") };
for (Account a : all) {
a.monthEnd(); // one call...
System.out.println(a.name + ": " + a.balance);
}
}
}
Output:
Aman: 1000
Riya: 1010
Kabir: 950
The array's type is Account, but each element is a different real object, and a.monthEnd() ran each object's own version. Add a FixedDeposit class tomorrow and this loop doesn't change.
Upcasting: storing a child object in a parent-type variable (Account a = new SavingsAccount("Riya")). It is always safe and automatic, because a savings account is an account. The cost: through an Account variable you can only call methods that Account declares.
Two kinds of polymorphism, two kinds of binding
Binding means linking a method call to the actual code that will run.
| Compile-time polymorphism | Runtime polymorphism | |
|---|---|---|
| Made by | overloading (methods, operators) | overriding |
| Decided | by the compiler, from the arguments' types | while running, from the real object |
| Binding | static binding (early binding) | dynamic binding (late binding) |
| Example | deposit(500) vs deposit(1000, "salary") |
a.monthEnd() on Savings vs Current |
In Java, static, private and final methods cannot be overridden, so they are always bound early. Every other instance method is bound late.
Problem 5: getting the child back (downcasting)
Downcasting is converting a parent-type reference back to a child type, with a cast in brackets: (SavingsAccount) a. It compiles, but it is only correct if the real object really is that child:
class Account {
int balance = 1000;
}
class SavingsAccount extends Account {
double rate = 0.04;
}
class CurrentAccount extends Account {
int fee = 50;
}
public class Main {
public static void main(String[] args) {
Account a = new SavingsAccount(); // upcasting
SavingsAccount s = (SavingsAccount) a; // downcasting
System.out.println("rate: " + s.rate);
Account b = new CurrentAccount();
SavingsAccount t = (SavingsAccount) b; // wrong!
System.out.println("rate: " + t.rate);
}
}
Output:
rate: 0.04
Exception in thread "main" java.lang.ClassCastException: class CurrentAccount cannot be cast to class SavingsAccount (CurrentAccount and SavingsAccount are in unnamed module of loader 'app')
at Main.main(Main.java:20)
The first cast works. The second compiles but fails at runtime with a ClassCastException, because a current account is not a savings account. The safe way is to check first with instanceof:
if (b instanceof SavingsAccount s) { // Java 16+ pattern: test and cast in one step
System.out.println("rate: " + s.rate);
}
Problem 6: under the hood (virtual functions, vtable, vptr)
In C++, the same idea gives a surprise:
#include <iostream>
using namespace std;
class Account {
public:
void monthEnd() { cout << "Account: nothing" << endl; }
};
class Savings : public Account {
public:
void monthEnd() { cout << "Savings: +1% interest" << endl; }
};
int main() {
Savings s;
Account* p = &s; // parent pointer, child object
p->monthEnd(); // which one runs?
}
Output:
Account: nothing
The parent's version ran on a Savings object. By default C++ uses static binding: the pointer's type is Account*, so the compiler wired the call to Account::monthEnd. (A pointer is a variable that holds a memory address; p->monthEnd() calls a method through it.)
The fix: virtual. A virtual function is a method chosen at runtime by the real object. Mark it virtual in the parent; override in the child asks the compiler to check it. In Java, every overridable method already behaves like a virtual function.
#include <iostream>
using namespace std;
class Account {
public:
virtual void monthEnd() { cout << "Account: nothing" << endl; }
};
class Savings : public Account {
public:
void monthEnd() override { cout << "Savings: +1% interest" << endl; }
};
class Plain { int balance; void f() { } };
class Virtual { int balance; virtual void f() { } };
int main() {
Savings s;
Account* p = &s;
p->monthEnd();
cout << "Plain: " << sizeof(Plain) << " bytes" << endl;
cout << "Virtual: " << sizeof(Virtual) << " bytes" << endl;
}
Output:
Savings: +1% interest
Plain: 4 bytes
Virtual: 16 bytes
The class with one virtual function is 12 bytes bigger. Here's why:
- For each class that has virtual functions, the compiler builds one table of addresses of that class's versions: the virtual table (vtable).
Savings's vtable says "monthEnd →Savings::monthEnd". - Inside each object, the compiler adds a hidden pointer to its class's vtable: the vptr.
- A virtual call becomes: object → vptr → vtable → jump to the address found there.
- On a 64-bit machine a pointer is 8 bytes. 8 (vptr) + 4 (
int balance) = 12, and the compiler adds 4 bytes of padding (filler bytes so the next object starts at an address that is a multiple of 8, which the CPU reads fastest) = 16.
| vtable | vptr | |
|---|---|---|
| How many | one per class (with virtual functions) | one per object |
| Holds | addresses of the class's virtual functions | the address of its class's vtable |
| Made by | the compiler | the constructor sets it |
The price of runtime polymorphism: one pointer per object and one extra memory lookup per call. Adding more virtual functions makes the vtable longer, but each object still has just one vptr.
Problem 7: an account of no type (abstract classes)
The bank decides every account must be savings or current. A plain Account object makes no sense, and a new child class must not forget monthEnd.
- An abstract class (
abstract class Account) is an incomplete class: you cannot create objects of it, only of its children. It can still have fields, constructors and normal methods. - An abstract method (
abstract void monthEnd();) has only a signature (name, parameters, return type) and no body. Every non-abstract child must provide it.
abstract class Account {
String name;
int balance;
Account(String name, int balance) {
this.name = name;
this.balance = balance;
}
abstract void monthEnd(); // no body: children MUST write it
}
class SavingsAccount extends Account {
SavingsAccount(String n, int b) { super(n, b); }
void monthEnd() { balance += balance / 100; }
}
public class Main {
public static void main(String[] args) {
Account s = new SavingsAccount("Riya", 1000);
s.monthEnd();
System.out.println(s.name + ": " + s.balance);
Account a = new Account("Aman", 1000);
}
}
Output:
Main.java:21: error: Account is abstract; cannot be instantiated
Account a = new Account("Aman", 1000);
^
1 error
Instantiate means "create an instance (an object) of". Remove the last line and the program runs:
Riya: 1010
Pure virtual functions (C++)
C++ has no abstract keyword. Writing = 0 after a virtual function makes it a pure virtual function (no body in this class); any class with at least one becomes abstract:
#include <iostream>
using namespace std;
class Account {
public:
virtual void monthEnd() = 0; // pure virtual
};
int main() {
Account a;
}
Output:
main.cpp: In function ‘int main()’:
main.cpp:10:13: error: cannot declare variable ‘a’ to be of abstract type ‘Account’
10 | Account a;
| ^
main.cpp:4:7: note: because the following virtual functions are pure within ‘Account’:
4 | class Account {
| ^~~~~~~
main.cpp:6:18: note: ‘virtual void Account::monthEnd()’
6 | virtual void monthEnd() = 0; // pure virtual
| ^~~~~~~~
Problem 8: two parents, and rules that must hold
Multiple inheritance in Java: not allowed
class Account { }
class Loan { }
class HomeLoanAccount extends Account, Loan { }
public class Main {
public static void main(String[] args) { }
}
Output:
Main.java:4: error: '{' expected
class HomeLoanAccount extends Account, Loan { }
^
1 error
The diamond problem (C++)
C++ allows multiple inheritance. Customer and Employee both extend Person, and StaffCustomer extends both. Drawn out, the four classes form a diamond:
Person
/ \
Customer Employee
\ /
StaffCustomer
#include <iostream>
using namespace std;
class Person { public: string name = "Riya"; };
class Customer : public Person { };
class Employee : public Person { };
class StaffCustomer : public Customer, public Employee { };
int main() {
StaffCustomer r;
cout << r.name << endl; // whose name?
}
Output:
main.cpp: In function ‘int main()’:
main.cpp:11:15: error: request for member ‘name’ is ambiguous
11 | cout << r.name << endl; // whose name?
| ^~~~
main.cpp:4:33: note: candidates are: ‘std::string Person::name’
4 | class Person { public: string name = "Riya"; };
| ^~~~
main.cpp:4:33: note: ‘std::string Person::name’
The object contains two Person parts (one through each middle class), so it has two names and the compiler can't choose. This is the diamond problem. C++'s fix is virtual inheritance: class Customer : virtual public Person (and the same for Employee) makes the middle classes share one Person part.
#include <iostream>
using namespace std;
class Person { public: string name = "Riya"; };
class Customer : virtual public Person { };
class Employee : virtual public Person { };
class StaffCustomer : public Customer, public Employee { };
int main() {
StaffCustomer r;
cout << r.name << endl; // one shared Person
}
Output:
Riya
Interfaces (Java)
Real-life example: the wall socket. Its shape is a standard: a promise of what fits, not a machine. A fan, a charger and a kettle each keep that promise their own way, and one device can fit two standards without any clash.
- An interface lists methods that a class promises to have. It has no instance fields (no state). Its methods are
publicand, unless markeddefaultorstatic, have no body. - A class keeps the promise with
implementsand must write every method, aspublic. - A class can extend one class but implement many interfaces. Because interfaces carry no state, there is no duplicated data and no diamond of fields.
interface Printable {
void printStatement(); // a promise, no body
}
interface Taxable {
int tax();
}
class SavingsAccount implements Printable, Taxable {
int interest = 4000;
public void printStatement() {
System.out.println("Interest earned: " + interest);
}
public int tax() { return interest / 10; } // 10% tax
}
public class Main {
public static void main(String[] args) {
SavingsAccount s = new SavingsAccount();
Printable p = s;
Taxable t = s;
p.printStatement();
System.out.println("Tax: " + t.tax());
}
}
Output:
Interest earned: 4000
Tax: 400
| Abstract class | Interface | |
|---|---|---|
| Meaning | an is-a family that shares code | a can-do ability unrelated classes share |
| Fields | any | only constants (static final) |
| Constructors | yes | no |
| Methods | abstract and normal | abstract; default and static methods may have bodies |
| How many per class | extend one | implement many |
| Keyword | extends |
implements |
final and sealed
The bank's rule is a minimum balance of ₹500. With overriding, any child could quietly rewrite it. A final method cannot be overridden:
class Account {
int balance = 1000;
final int minBalance() { return 500; } // rule: can't change
}
class SavingsAccount extends Account {
int minBalance() { return 0; } // try to bypass it
}
public class Main {
public static void main(String[] args) {
System.out.println(new SavingsAccount().minBalance());
}
}
Output:
Main.java:7: error: minBalance() in SavingsAccount cannot override minBalance() in Account
int minBalance() { return 0; } // try to bypass it
^
overridden method is final
1 error
- final method: no child may override it.
- final class: no class may extend it at all (Java's own
Stringis final). - final variable: assigned once, then it can't change.
- sealed class (Java 17 and later): lists exactly which classes may extend it:
sealed class Account permits SavingsAccount, CurrentAccount { }. Each permitted child must itself befinal,sealedornon-sealed. - In C#, the word
sealedmeans what Java'sfinalmeans for classes. In C++,finalafter a class name or virtual function does the same job.
Common mistakes (and the real output)
| Mistake | Real output | Why | Fix |
|---|---|---|---|
Child constructor without super(name, balance) |
error: constructor Account in class Account cannot be applied to given types; |
the parent part must be built first; Java tried super() |
super(name, balance); as the first line |
(SavingsAccount) on a CurrentAccount |
java.lang.ClassCastException: class CurrentAccount cannot be cast to class SavingsAccount |
the real object is not that child | check with instanceof |
C++ override without virtual in the parent |
Account: nothing |
static binding by the pointer's type | virtual in the parent, override in the child |
new Account(...) on an abstract class |
error: Account is abstract; cannot be instantiated |
abstract classes have no objects | create a child object |
extends Account, Loan |
error: '{' expected |
Java classes have one parent | use interfaces |
| Two copies of a grandparent in C++ | error: request for member 'name' is ambiguous |
diamond problem | virtual public Person |
Overriding a final method |
error: minBalance() in SavingsAccount cannot override minBalance() in Account / overridden method is final |
final forbids overriding | don't override, or remove final |
| Changing only the return type to "overload" | error: method g() is already defined in class D |
return type alone doesn't distinguish overloads | change the parameters |
Mini project: the bank's month-end run
Build an abstract Account with a final minimum-balance rule and an abstract monthEnd(), three children, and one polymorphic loop.
abstract class Account {
String name; int balance;
Account(String name, int balance) { this.name = name; this.balance = balance; }
final int minBalance() { return 500; }
abstract void monthEnd();
public String toString() { return name + ": " + balance; }
}
class SavingsAccount extends Account {
SavingsAccount(String n, int b) { super(n, b); }
void monthEnd() { balance += balance / 100; } // +1%
}
class CurrentAccount extends Account {
CurrentAccount(String n, int b) { super(n, b); }
void monthEnd() { balance -= 50; } // fee
}
class FixedDeposit extends Account {
FixedDeposit(String n, int b) { super(n, b); }
void monthEnd() { balance += balance / 50; } // +2%
}
public class Main {
public static void main(String[] args) {
Account[] all = { new SavingsAccount("Riya", 10000),
new CurrentAccount("Kabir", 600),
new FixedDeposit("Aman", 50000) };
for (Account a : all) {
a.monthEnd();
String warn = a.balance < a.minBalance() ? " (below minimum!)" : "";
System.out.println(a + warn);
}
}
}
Output:
Riya: 10100
Kabir: 550
Aman: 51000
Extend it: make the loop print "below minimum" for Kabir after two months (call monthEnd() twice), and add an interface Printable that only FixedDeposit implements.
Practice
1. Add a FixedDeposit that overrides monthEnd() with 2% interest.
Solution
class FixedDeposit extends Account {
FixedDeposit(String n) { super(n); }
@Override
void monthEnd() { balance += balance / 50; } // 2% of balance
}
With the OVERRIDE demo's Account (balance 1000), one month end gives 1020. The loop in main does not change.
2. Write an overloaded withdraw(int amount, String reason) next to withdraw(int amount).
Solution
void withdraw(int amount) { balance -= amount; }
void withdraw(int amount, String reason) {
withdraw(amount); // reuse version 1
System.out.println("Withdrew " + amount + " for " + reason);
}
Same name, different parameter lists: overloading, chosen at compile time.
3. Make the downcast in the CAST demo safe.
Solution
Account b = new CurrentAccount();
if (b instanceof SavingsAccount t) {
System.out.println("rate: " + t.rate);
} else {
System.out.println("not a savings account");
}
Prints not a savings account instead of crashing.
4. Predict sizeof of a C++ class with an int and two virtual functions on a 64-bit machine.
Solution
16 bytes, the same as with one virtual function. Each object has one vptr (8 bytes) no matter how many virtual functions there are; only the class's vtable gets longer. 8 + 4 + 4 bytes of padding = 16.
5. Which of these are overriding and which overloading? void f(int) in parent, child has (a) void f(int), (b) void f(double), (c) int f(int).
Solution
(a) overriding (same signature). (b) overloading: a new method with a different parameter type, inherited f(int) still exists. (c) compile error: same parameters but an incompatible return type. javac says f(int) in C cannot override f(int) in P / return type int is not compatible with void.
Quick quiz
class A { void hi() { System.out.print("A"); } }
class B extends A {
void hi() { System.out.print("B"); }
void hi(int n) { System.out.print(n); }
}
// in main:
A x = new B();
x.hi();
new B().hi(7);
A. A7 B. B7 C. AB D. compile error
Answer
B. B7. x is an A variable holding a B object; hi() is overridden, so dynamic binding runs B's version and prints B. hi(7) matches the overload hi(int) at compile time and prints 7.
Interview questions
- What is inheritance? Name its types. Reusing a parent class's fields and methods in a child class (is-a). Single, multilevel, hierarchical, multiple, hybrid; Java classes don't support multiple/hybrid.
- Overloading vs overriding? Overloading: same name, different parameters, compile time, usually same class. Overriding: same signature in a child class, runtime, needs inheritance.
- Compile-time vs runtime polymorphism? Compile-time = overloading, resolved by the compiler (static/early binding). Runtime = overriding, resolved from the real object (dynamic/late binding).
- Can you override a static method in Java? No. A static method with the same signature in the child hides the parent's; which one runs depends on the reference type, not the object.
- Can you override a private or final method? No. Private methods aren't visible to the child; final methods are forbidden from being overridden.
- Why does Java not support multiple inheritance of classes? To avoid the diamond problem (ambiguous duplicate state and methods). Interfaces give multiple inheritance of type without duplicated state.
- What is a virtual function? How does it work? A function resolved at runtime by the real object. Each class has a vtable of function addresses; each object has a vptr to its class's vtable; a call goes object → vptr → vtable → function.
- Abstract class vs interface? See the table above. Abstract class: shared code and state, one per class, constructors allowed. Interface: a contract of abilities, many per class, no instance state.
- What is the diamond problem and how does C++ solve it? A class inheriting the same grandparent through two paths gets two copies of it, making members ambiguous. Virtual inheritance shares one copy.
- What does
superdo? Calls the parent's constructor (super(...), first line) or reaches a parent's member (super.method()). - In what order do constructors and destructors run in inheritance? Constructors: parent first, then child. Destructors (C++): child first, then parent.
- What is upcasting and downcasting? Upcasting: child object into a parent-type reference (safe, automatic). Downcasting: back to the child type with a cast (needs the object to really be that child, else
ClassCastException).
Glossary
| Term | Meaning in plain words | Example |
|---|---|---|
| Inheritance | A class receiving all fields and methods of another class and adding its own | class SavingsAccount extends Account |
| Parent / base class / superclass | The class others build on | Account |
| Child / derived class / subclass | The class that builds on a parent | SavingsAccount |
| is-a relationship | "A child is a kind of parent"; the test for inheritance | a savings account is an account |
| Single inheritance | One parent, one child | Account → SavingsAccount |
| Multilevel inheritance | A chain of inheritance | Account → SavingsAccount → KidsSavings |
| Hierarchical inheritance | One parent, many children | Savings and Current extend Account |
| Multiple inheritance | One child with two or more parents | C++: class C : public A, public B |
| Hybrid inheritance | A mix of the types above | multilevel + multiple |
| Diamond problem | A class gets two copies of a grandparent through two parents, so members are ambiguous | StaffCustomer has two Person parts |
| Virtual inheritance | C++ way to share one copy of a common grandparent | class Customer : virtual public Person |
| super keyword | Refers to the parent: super(...) calls its constructor, super.x its member |
super(name, balance); |
| Constructor chaining | Constructors calling the next constructor up (or in the same class with this(...)) |
parent built, then child |
| Method overloading | Same method name, different parameter lists | deposit(int), deposit(int, String) |
| Operator overloading | Giving an operator a meaning for your own type (C++) | Money operator+(const Money&) |
| Method overriding | A child's own version of a parent method with the same signature | SavingsAccount.monthEnd() |
| @Override | Annotation asking the compiler to check a method really overrides one | @Override void monthEnd() |
| Signature | A method's name and parameter types | deposit(int, String) |
| Polymorphism | One call, many forms of behaviour, chosen by the object or the arguments | a.monthEnd() on three types |
| Compile-time polymorphism | Polymorphism decided by the compiler (overloading) | deposit(500) picks version 1 |
| Runtime polymorphism | Polymorphism decided while running (overriding) | a.monthEnd() on a Savings object |
| Binding | Linking a method call to the code that runs | — |
| Static (early) binding | Binding done at compile time | overloads, static/private/final methods |
| Dynamic (late) binding | Binding done at runtime from the real object | overridden methods |
| Upcasting | Putting a child object in a parent-type variable | Account a = new SavingsAccount() |
| Downcasting | Casting a parent-type reference back to a child type | (SavingsAccount) a |
| ClassCastException | Runtime error when a cast doesn't match the real object | casting a CurrentAccount to SavingsAccount |
| instanceof | Checks an object's real type before a cast | if (b instanceof SavingsAccount s) |
| Pointer | A variable holding a memory address (C/C++) | Account* p = &s; |
| Virtual function | A C++ method resolved at runtime by the real object | virtual void monthEnd() |
| override (C++) | Keyword asking the compiler to check a function overrides a virtual one | void monthEnd() override |
| vtable | A per-class table of addresses of its virtual functions | Savings's vtable → Savings::monthEnd |
| vptr | A hidden per-object pointer to its class's vtable | the extra 8 bytes |
| Padding | Filler bytes the compiler adds so data lines up in memory | 4 bytes in our 16-byte object |
| Abstract class | A class you can't create objects of; children fill in its gaps | abstract class Account |
| Abstract method | A method with no body that children must write | abstract void monthEnd(); |
| Instantiate | Create an instance (object) of a class | new SavingsAccount(...) |
| Pure virtual function | C++ virtual function with = 0, making the class abstract |
virtual void monthEnd() = 0; |
| Interface | A list of methods a class promises to have, with no state | interface Taxable { int tax(); } |
| implements | Keyword for a class keeping an interface's promise | class S implements Printable, Taxable |
| Annotation | A label in code read by the compiler or tools | @Override |
| final (method/class) | Cannot be overridden / cannot be extended | final int minBalance() |
| sealed class | A class that lists exactly which classes may extend it | sealed class Account permits SavingsAccount |
| Current account | A bank account for frequent business transactions, usually without interest | CurrentAccount with a fee |
Summary
- Inheritance (
extends) reuses a parent's code in a child; use it only for a true is-a. Five types: single, multilevel, hierarchical, multiple, hybrid (Java classes: no multiple). - A child object contains a parent part, built first by
super(...): constructor chaining. - Overloading = same name, different parameters, decided at compile time (static binding). C++ also allows operator overloading.
- Overriding = a child's version of a parent method, decided at runtime by the real object (dynamic binding). That's runtime polymorphism. Upcasting is always safe; downcasting needs
instanceof. - C++ needs
virtualfor runtime polymorphism; it works through a per-class vtable and a per-object vptr (here: 4 → 16 bytes). - Abstract classes (and C++ pure virtual functions) can't be instantiated and force children to fill in methods. Interfaces are contracts with no state; a class implements many.
- Multiple inheritance of classes causes the diamond problem; C++ fixes it with virtual inheritance, Java avoids it with interfaces.
- final stops overriding or extending; sealed limits who may extend.
Sources for version facts: sealed classes became a permanent Java feature in Java SE 17 (JEP 409) and pattern matching for instanceof in Java SE 16 (JEP 394), per Oracle's Java Language Changes Summary. That String is final was checked with Modifier.toString(String.class.getModifiers()), which prints public final.
Next episode: OOP 3: has-a vs is-a, composition, coupling and cohesion, SOLID, deep copies, exceptions, generics and your first design patterns.