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

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? |
|
|
Abstraction | What must a caller know? |
| Abstraction is not simply hiding every field |
Inheritance | When is one type substitutable for another? |
| Code reuse alone does not prove an is-a relation |
Polymorphism | Which implementation fulfils one contract at run time? |
| 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

Use this Java setup:
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:
refhas static typeAand points to aBobject.Bdoes not overrideg(), so the inheritedA.g()body runs.The
f()call inside that body is dynamically dispatched toB.f().B.f()readsB.x = 5, so it returns5 x 2 = 10.The unqualified
xwritten inA.g()denotesA.x = 2, so the result is10 + 2 = 12.
Fields are hidden rather than overridden in this Java example. Change only the lookup rules, and the results change:
Language case | Selected | Field used inside | Field used inside | Result |
|---|---|---|---|---|
Java |
|
|
|
|
C++ with virtual |
|
|
|
|
C++ with non-virtual |
|
|
|
|
Python |
|
|
|
|
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.

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, soA.g()usesA.x = 2.All C++ calls are dynamic: Non-virtual C++ is wrongly predicted as
12. Markfas 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()prints12.B.f()supplies10, and thexinA.g()supplies2.Check B: Remove
virtualfrom the C++f, and the result is4. Both lookups insideA::g()useA.Check C: The specified Python
B().g()returns15. Bothself.f()andself.xuse theBobject.Check D: A
Robotwith aBatteryuses composition. After five steps consuming8units each from60, the battery has20units.
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.
Keep learning
Object-Oriented Programming (OOP): Four Pillars and a Worked Dynamic-Binding Example
Build a precise OOP mental model, then follow two Employee objects through a Java program to see overloading, overriding and runtime dispatch in action.
Object-Oriented Programming: Classes, Objects and Inheritance with a Worked Java Example
Trace two Java objects from construction to output, and see how independent state, inheritance and runtime method dispatch work together.
Object-Oriented Programming (OOPS): Core Concepts with a Worked C++ Example
Build one connected OOP model, then trace how two account objects respond differently through the same C++ base-class interface.
C++ Cross-Concept Questions Explained: Scope, Dispatch and Object Lifetime
Trace one well-defined C++ program from construction to destruction, then change one line at a time to see which language rule controls each output token.





