Classes & Objects Questions with Answers

26 practice questions on Classes & Objects (OOP Concepts) with answers and step-by-step solutions. Try 10 samples below, then practise all 26 free in the AptiNest app.

Sample questions

Question 1Easy

What does this Python code print?

class C:
    n = 0

a = C()
a.n = 5
print(C.n, a.n, C().n)
  1. 5 5 0
  2. 5 5 5
  3. 0 5 5
  4. 0 5 0

Answer: D. 0 5 0

Explanation

a.n = 5 creates an instance attribute on a only. The class attribute C.n stays 0, and a fresh instance still sees the class value.

Step-by-step solution

  1. a.n = 5 creates an instance attribute n on a; the class attribute C.n stays 0.
  2. C.n is 0, a.n is 5, and C().n is a new object reading the class value 0.
  3. The output is "0 5 0"; index 3 is correct.

Why the other options are wrong

  • A. C.n was never changed; only a's own attribute is 5.
  • B. C.n is still 0, not 5.
  • C. a.n is 5, but C.n and C().n are both 0, not 5.

Tip: Assigning through an instance creates its own attribute and does not change the class attribute.

Question 2Easy

Which of the following best describes the state of an object?

  1. The memory address of its class definition
  2. The values currently held in its fields
  3. The set of methods its class defines
  4. The name of its class

Answer: B. The values currently held in its fields

Explanation

State is the data an object holds at a point in time; behaviour is given by methods and identity distinguishes it from other objects.

Step-by-step solution

  1. State refers to the data an object holds.
  2. This includes values stored in its fields.
  3. Fields contain the current information of the object.
  4. Methods define behaviour, not state.
  5. Name and class are for identity, not state.

Why the other options are wrong

  • A. The class definition's memory address identifies where the class lives, not the object's state.
  • C. Methods are shared behaviour of the class; they are not the state each object holds.
  • D. A class name identifies the type, not the values an object holds right now.

Tip: Remember: State = Data, Behaviour = Methods, Identity = Name/Class.

Question 3Easy

What is the output of this Java program?

class Point {
    int x;
    Point(int x) { this.x = x; }
}
public class Main {
    public static void main(String[] args) {
        Point p = new Point(5);
        Point q = new Point(5);
        Point r = p;
        System.out.println((p == q) + " " + (p == r));
    }
}
  1. false false
  2. true false
  3. true true
  4. false true

Answer: D. false true

Explanation

== compares references. p and q are different objects (equals() is not overridden either), while r refers to the same object as p.

Step-by-step solution

  1. p and q come from two separate new Point(5) calls - two different objects in memory.
  2. Point never overrides equals(), so == on these objects compares references (identity), not field values.
  3. p == q is therefore false, since they are different objects even though x happens to match.
  4. r = p simply copies the reference, so r points at the exact same object as p, making p == r true.

Why the other options are wrong

  • A. p == r being false would require r to be a different object from p, but r was explicitly assigned from p, making them identical references.
  • B. p == q being true would require Point to override equals() (it doesn't) or p and q to be the same object (they came from two separate 'new' calls, so they aren't).
  • C. p == q being true is wrong for the same reason: without an overridden equals(), two separately created objects are never == even if their fields match.

Tip: == on objects without an overridden equals(): same object -> true, merely equal-looking objects -> false.

Question 4Easy

What is a constructor?

  1. A special method called automatically to initialise a new object
  2. A method that destroys an object and frees its memory when it goes out of scope
  3. A method that must be called manually after creating an object
  4. A static method that returns the class name

Answer: A. A special method called automatically to initialise a new object

Explanation

Constructors have the class's name (in Java/C++), no return type, and run when the object is created.

Step-by-step solution

  1. A constructor is a special method used to initialise an object when it is created.
  2. It runs automatically without needing to be called manually.
  3. Constructors have the same name as the class and no return type.
  4. They are not static and are called using the new keyword.
  5. The correct answer is A special method called automatically to initialise a new object.

Why the other options are wrong

  • B. That describes a destructor or finaliser that frees an object, not a constructor, which sets up a new object.
  • C. Constructors run automatically when an object is created, so they do not need to be called manually.
  • D. Constructors are not static and do not return a class name; they set up the new object's fields.

Tip: Remember: constructors are automatic, have no return type, and share the class name.

Question 5Medium

What does this Python code print?

class Bag:
    def __init__(self):
        self.items = []
    def __len__(self):
        return len(self.items)

b = Bag()
print("full" if b else "empty", end=" ")
b.items.append(1)
print("full" if b else "empty")
  1. full full
  2. empty full
  3. full empty
  4. empty empty

Answer: B. empty full

Explanation

Without __bool__, Python uses __len__ for truth testing: length 0 is falsy, length 1 is truthy.

Step-by-step solution

  1. The first check bool(b) uses __len__, which returns 0, so b is falsy and "empty " is printed.
  2. After the append __len__ returns 1, so b is truthy and "full" is printed.
  3. The output is "empty full"; index 1 is correct.

Why the other options are wrong

  • A. The first check has 0 items, which is falsy, so it is not full.
  • C. The second check runs after the append, so the length is 1 and b is full.
  • D. The second check is after an item is added, so it prints full.

Tip: Python decides truthiness with __bool__ first and then __len__; a length of zero is False.

Question 6Medium

What is the output of this Java program?

class A {
    A() { System.out.print("A"); }
}
class B extends A {
    B() { System.out.print("B"); }
}
class C extends B {
    C() { System.out.print("C"); }
}
public class Main {
    public static void main(String[] args) { new C(); }
}
  1. CBA
  2. C
  3. ABC
  4. AC

Answer: C. ABC

Explanation

Each constructor implicitly calls super() first, so constructors run from the top of the hierarchy down: A, then B, then C.

Step-by-step solution

  1. Constructor of class A runs first, printing 'A'.
  2. Constructor of class B runs next, printing 'B'.
  3. Constructor of class C runs last, printing 'C'.
  4. Order is top to bottom in hierarchy: A, then B, then C.
  5. Final output is ABC.

Why the other options are wrong

  • A. Superclass constructors run first, so A prints before B and C, and the order is not reversed.
  • B. Constructors of all superclasses run as well, so A and B also print before C.
  • D. B's constructor is also called in the chain and prints B, so the output must include B.

Tip: Remember constructor order follows inheritance chain.

Question 7Medium

What is the output of this Java program?

import java.util.*;
class P {
    int id;
    P(int id) { this.id = id; }
    @Override public boolean equals(Object o) {
        return o instanceof P && ((P) o).id == id;
    }
    @Override public int hashCode() { return id; }
}
public class Main {
    public static void main(String[] args) {
        Set<P> s = new HashSet<>();
        s.add(new P(1));
        s.add(new P(1));
        s.add(new P(2));
        System.out.println(s.size());
    }
}
  1. 0
  2. 3
  3. 2
  4. 1

Answer: C. 2

Explanation

equals() and hashCode() are both overridden consistently, so the two P(1) objects are treated as equal and the set keeps only one of them, plus P(2).

Step-by-step solution

  1. A HashSet keeps only unique elements, using equals and hashCode.
  2. The two new P(1) objects are equal, so the second add is ignored.
  3. P(2) is new, so the set holds 2 elements; the correct answer is option C.

Why the other options are wrong

  • A. The set has elements, so its size is not 0.
  • B. The two P(1) objects are equal, so only one is kept.
  • D. P(2) is different from P(1), so the size is not 1.

Tip: Override equals and hashCode together to get correct set behaviour.

Question 8Medium

What does the 'this' reference refer to inside an instance method?

  1. The most recently created object of the class
  2. The parent class object
  3. The class in which the method is defined
  4. The object on which the method was invoked

Answer: D. The object on which the method was invoked

Explanation

'this' (or self in Python) is the receiver of the current call, which lets the method read and modify that particular object's fields.

Step-by-step solution

  1. When obj.method() runs, this inside that method is bound to obj - the exact object the call was made on.
  2. Two different objects calling the same method get two different this values, each pointing at itself.
  3. This lets the method read and modify that particular object's own fields without needing to name it explicitly.

Why the other options are wrong

  • A. 'this' isn't tied to creation order - it's whichever object received THIS particular call, even if it was created long ago.
  • B. The parent class's object (if any) is reached via 'super', not 'this'.
  • C. The class itself (as opposed to an instance) is reached via something like getClass(), not 'this'.

Tip: 'this' = whoever was standing to the left of the dot when the method was called.

Question 9Hard

What does this Python code print?

class K:
    def __init__(self, v):
        self.v = v
    def __eq__(self, other):
        return self.v == other.v

try:
    s = {K(1), K(1)}
    print(len(s))
except TypeError:
    print("TypeError")
  1. AttributeError
  2. 2
  3. 1
  4. TypeError

Answer: D. TypeError

Explanation

Defining __eq__ without __hash__ sets __hash__ to None, which makes instances unhashable, so building the set raises TypeError.

Step-by-step solution

  1. Defining __eq__ on a class makes Python automatically set that class's __hash__ to None.
  2. This happens because the default identity-based hash would now be inconsistent with the new, custom equality.
  3. A set needs to hash its elements to store them, so building {K(1), K(1)} raises TypeError, which the except clause catches and prints.

Why the other options are wrong

  • A. No AttributeError occurs here - accessing other.v inside __eq__ works fine, since both operands are K instances with a .v attribute.
  • B. A length of 2 would mean both K(1) objects were stored as distinct set elements, but the error happens before any set can even be built.
  • C. A length of 1 would mean Python successfully deduplicated the two equal K(1) objects using __eq__, but it never gets that far - the objects can't even be hashed to go into the set.

Tip: Override __eq__ in Python? You must also define __hash__ yourself, or the class becomes unhashable.

Question 10Hard

A class has 3 instance fields and 2 static fields. If 5 objects are created, how many field storage slots exist in total (ignoring inherited fields)?

  1. 10
  2. 17
  3. 15
  4. 25

Answer: B. 17

Explanation

Instance fields: 5 objects x 3 = 15. Static fields exist once for the class: 2. Total 15 + 2 = 17.

Step-by-step solution

  1. Instance fields: 5 objects × 3 = 15.
  2. Static fields: 2 exist once for the class.
  3. Total slots: 15 + 2 = 17.

Why the other options are wrong

  • A. 10 counts 5 objects times 2 static fields, but static fields are stored once per class.
  • C. 15 leaves out the two static fields, which are stored once for the class.
  • D. 25 would treat all five fields as per-object, but the two static fields are stored once.

Tip: Multiply instance fields by object count, add static fields once.

Practise all 26 questions free

The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.

Open this topic in the app →

Related topics

See all OOP Concepts topics · All topics