WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Software Engineering · Basic · question 10 of 100

Describe the difference between inheritance and composition in object-oriented programming.?

📕 Buy this interview preparation book: 100 Software Engineering questions & answers — PDF + EPUB for $5

In object-oriented programming, inheritance and composition are two fundamental ways of creating relationships between classes.

Inheritance is a mechanism where one class (the subclass) is derived from another class (the superclass), inheriting all of its properties and methods. This means that the subclass can access and use all the public and protected members of the superclass. In other words, inheritance is a "is-a" relationship, where the subclass is a type of the superclass.

For example, say we have a superclass called ‘Animal‘ and a subclass called ‘Cat‘. The ‘Cat‘ class inherits all the properties and methods defined in the ‘Animal‘ class, such as ‘eat()‘ and ‘sleep()‘. The ‘Cat‘ class can also define additional methods or properties specific to it.

class Animal {
   void eat() {
      // do something
   }

   void sleep() {
      // do something
   }
}

class Cat extends Animal {
   void meow() {
      // do something
   }
}

On the other hand, composition is a mechanism where one object is composed of other objects. This means that the composed object has an instance of another object and provides a way to access or use its properties and methods. In other words, composition is a "has-a" relationship, where the composed object has a certain behavior or property.

For example, say we have a class called ‘Car‘ that has a ‘Engine‘ instance. The ‘Car‘ class can access and use the properties and methods defined in the ‘Engine‘ class, such as ‘start()‘ and ‘stop()‘.

class Engine {
   void start() {
      // do something
   }

   void stop() {
      // do something
   }
}

class Car {
   private Engine engine;

   void start() {
      engine.start();
   }

   void stop() {
      engine.stop();
   }
}

In summary, inheritance is a way of creating a new class hierarchy by deriving one class from another, while composition is a way of creating a new class by combining existing objects of other classes. Both mechanisms have their own advantages and disadvantages and should be used based on the specific requirements of the problem being solved.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Software Engineering interview — then scores it.
📞 Practice Software Engineering — free 15 min
📕 Buy this interview preparation book: 100 Software Engineering questions & answers — PDF + EPUB for $5

All 100 Software Engineering questions · All topics