1. LPU MCA Semester 1
  2. CAB106
  3. Unit 2

CAB106 · Unit 2: Classes and objects

Built-in class functions and object relationships

12 practice questions

Key points

  • isinstance covers subclasses; type is exact
  • getattr accepts a default; dir includes inherited names
  • Composition owns the parts; aggregation shares them
  • Use inheritance for is-a and composition for has-a

Built-in helpers inspect objects: isinstance(obj, C) tests the class or any subclass, issubclass(B, A) tests inheritance, type(x) returns the exact class, hasattr, getattr(obj, name, default), setattr and delattr work with attributes by name, dir(x) lists all names including inherited ones, and vars(x) (or x.__dict__) lists only the object's own. isinstance accepts a tuple of types, and bool is a subclass of int.

Objects relate in three main ways:

RelationshipMeaningExample
Inheritance (is-a)Subclass specialises a parentDog is an Animal
Composition (has-a)Parts are owned and die with the wholeHouse and Rooms
Aggregation (has-a)Parts exist independentlyDepartment and Teachers

Association is the general term for any link between objects. Has-a relationships are built by storing one object in an attribute of another, and delegating work to it, as a Car calls self.engine.start(). Several wholes can share one part object in aggregation.

Exam trap: use inheritance only when the sentence 'X is a Y' is true. 'A car has an engine' calls for composition, not for deriving Car from Engine.

Try two questions

Question 1 · Tier 3, Apply

A Department holds Teacher objects, and the teachers keep existing when the Department closes. Which relationship is this?

  1. Composition, where the parts are destroyed with the whole
  2. Aggregation, where the parts exist independently of the whole
  3. Inheritance, where Teacher derives from Department
  4. Encapsulation, where every attribute is made private
Show the answer

B. Aggregation is a weaker has-a link in which the parts live on independently.

Why not A: Composition would destroy the teachers with the department.

Why not C: A teacher is not a kind of department.

Why not D: Encapsulation hides data; it does not describe containment.

Question 2 · Tier 3, Apply

A House creates its Rooms and they are destroyed when the House is destroyed. Which relationship is this?

  1. Aggregation, where the parts can outlive the whole
  2. Inheritance, where Room derives from House
  3. Overloading, where one name has several signatures
  4. Composition, where the parts cannot outlive the whole
Show the answer

D. In composition the whole owns its parts, so the parts end with it.

Why not A: In aggregation the parts exist independently of the whole.

Why not B: A room is not a kind of house, so inheritance does not fit.

Why not C: Overloading concerns method names, not containment.