Object-Oriented Programming Across Languages: Classes, Inheritance and Dynamic Dispatch

Trace one A/B hierarchy across Java, C++ and Python, then use precise tests for encapsulation, subtype inheritance, composition and polymorphism.

KnowledgeGate Team

Exam prep & CS education

Updated 25 Nov 20266 min read
Object-Oriented Programming Across Languages: Classes, Inheritance and Dynamic Dispatch

You may memorise encapsulation, abstraction, inheritance and polymorphism, yet still lose an output-tracing question. The usual problem is mixing up the reference type, run-time object, field lookup and method dispatch. A safer method is language-aware: identify the object and its contract, determine the applicable member-lookup rule, and only then calculate. The order matters because each rule narrows the next step. One shared example below produces 12 in Java and virtual C++, 4 in non-virtual C++, and 15 in Python.

Object-oriented programming connects state, behaviour and a contract

A class is a declared model of state, behaviour and a contract. An object is a run-time instance with its own identity and state. If Counter declares count and increment(), c1 can start with count = 2. Two calls to c1.increment() change its state to 2 + 1 + 1 = 4. Counter is the declaration, c1 the object, and 4 its current value, not its identity.

The call c1.increment() asks the object to perform behaviour, so callers need not repeat the update rule. OOP is not unrelated functions placed inside a class. State, behaviour and invariants should belong together.

In A ref = new B(), A is the static reference type and B the run-time object type. The language decides what can be named and which implementation runs. Continue with the broader OOP overview. It owns the four-pillar explanation; this post focuses on the same lookup problem across Java, C++ and Python.

The four OOP pillars answer different questions

Idea

Question answered

Exact example

Common confusion

Encapsulation

Who may change state, and through which operation?

BankAccount keeps balance private and accepts deposit(30), changing 70 to 100

private alone is not a complete invariant

Abstraction

What must a caller know?

Shape exposes area() without exposing the formula

Abstraction is not simply hiding every field

Inheritance

When is one type substitutable for another?

Rectangle is usable where Shape is expected

Code reuse alone does not prove an is-a relation

Polymorphism

Which implementation fulfils one contract at run time?

area() on Rectangle(4, 3) returns 12, while area() on Square(5) returns 25

Overloading and overriding are not the same

Encapsulation protects state, abstraction presents the operation, inheritance may establish a subtype, and run-time polymorphism selects an override. They may coexist, but are not synonyms. See the earlier OOP pillars and dynamic-binding overview. The classes-and-inheritance guide stays with a Java object trace; this post compares the lookup rules across languages.

What changes across programming languages

In these examples, compare five axes. No single feature makes a language universally "more object-oriented".

Language

Type checking

Member visibility

Inheritance model

Dispatch rule

Object lifetime

Java

Statically checked reference

Access modifiers

Classes plus interfaces

Instance methods are dynamically dispatched; fields are not polymorphic

Garbage-collected

C++

Statically checked pointer or reference

Access specifiers

Classes, including multiple inheritance

Virtual methods are dynamically dispatched; non-virtual calls are statically bound

Automatic, manual and RAII-managed lifetime

Python

Dynamically typed name

Convention plus language mechanisms

Multiple inheritance supported

Ordinary instance-method and attribute lookup is run-time

Garbage-collected with implementation-specific details

Do not transfer Java field hiding to Python, or assume C++ dispatch is dynamic unless the function is virtual. Types, scope and binding are language-design choices.

Worked example: one object model, four dispatch results

One A/B object model yields Java 12, virtual C++ 12, non-virtual C++ 4, and Python 15.

Use this Java setup:

java
class A {
    int x = 2;
    int f() { return x; }
    int g() { return f() + x; }
}

class B extends A {
    int x = 5;
    @Override int f() { return x * 2; }
}

A ref = new B();
System.out.println(ref.g());

Trace Java in five steps:

  1. ref has static type A and points to a B object.

  2. B does not override g(), so the inherited A.g() body runs.

  3. The f() call inside that body is dynamically dispatched to B.f().

  4. B.f() reads B.x = 5, so it returns 5 x 2 = 10.

  5. The unqualified x written in A.g() denotes A.x = 2, so the result is 10 + 2 = 12.

Fields are hidden rather than overridden in this Java example. Change only the lookup rules, and the results change:

Language case

Selected f

Field used inside f

Field used inside g

Result

Java

B.f

B.x = 5 inside f

A.x = 2 inside g

12

C++ with virtual f

B::f

B::x = 5 inside f

A::x = 2 inside g

12

C++ with non-virtual f

A::f

A::x = 2 inside f

A::x = 2 inside g

4

Python

B.f

B.x = 5 through self in f

B.x = 5 through self in g

15

Virtual C++ selects B::f: 10 + 2 = 12. Non-virtual C++ selects A::f: 2 + 2 = 4. Python resolves both self lookups through B: 10 + 5 = 15. Lookup rules determine these results, not compilation mode. The Java Course: Concepts, MCQs & Coding Questions offers a structured route.

Four lanes compare Java, virtual and non-virtual C++, and Python member lookup, ending at 12, 12, 4, and 15.

Inheritance versus composition: test is-a and has-a

Use inheritance when a child instance can satisfy the parent's promised contract without surprising the caller. Use composition when one object owns or delegates to another capability. This is a reasoning test, not a slogan.

Suppose a Battery starts with 60 energy units and a Robot has that battery. If move(5) consumes 8 units per step, consumption is 5 x 8 = 40, leaving 60 - 40 = 20 units. Robot is a Battery is false, while Robot has a Battery is true. Inheritance between them would misstate the domain.

If WarehouseRobot honours the complete Robot.move(steps) contract and adds route planning, then WarehouseRobot is a Robot may be a valid subtype. It should still receive its battery through composition. Real designs depend on invariants and behaviour, not English grammar alone.

OOP traps: identify the lookup question first

  • Private field means complete encapsulation: A setter may accept invalid state. Reject a negative count.

  • Inheritance means reuse: A has-a relation becomes a false subtype. Test substitution and consider composition.

  • Overloading equals overriding: Compile-time selection is confused with run-time dispatch. Record the signature and receiver separately.

  • Fields behave like virtual methods: Java is wrongly predicted as 15. Bind the field to its declaring code, so A.g() uses A.x = 2.

  • All C++ calls are dynamic: Non-virtual C++ is wrongly predicted as 12. Mark f as virtual or non-virtual before tracing.

Before using the numbers, fill this table:

Expression

Static context

Run-time object

Selected member

What is being evaluated?

Where is it written or typed?

Which object exists?

Which field or method rule selects it?

How assessments test cross-concept OOP

Exam-style tasks ask you to trace output, choose a valid subtype, distinguish overriding from overloading, repair an encapsulation failure, or compare composition with inheritance. Solve the member-lookup problem in front of you.

  • Check A: The Java ref.g() prints 12. B.f() supplies 10, and the x in A.g() supplies 2.

  • Check B: Remove virtual from the C++ f, and the result is 4. Both lookups inside A::g() use A.

  • Check C: The specified Python B().g() returns 15. Both self.f() and self.x use the B object.

  • Check D: A Robot with a Battery uses composition. After five steps consuming 8 units each from 60, the battery has 20 units.

Question practice for this cross-concept OOP subtopic is most useful after you annotate the static context, run-time object and selected member.

Object-oriented programming across languages: the short version and next step

Use five checks: identify each object and its current state, write the contract visible to the caller, test is-a versus has-a, mark the language's field and method lookup rules, then substitute the exact values. That method reconciles the central outputs: Java 12, C++ with virtual f 12, C++ with non-virtual f 4, and Python 15.

For language-specific practice, continue with the Java Course: Concepts, MCQs & Coding Questions. To browse a wider route, use Coding & Skill Development Courses.