Interview Q&A · Java · 3 questions in this topic

IS-A vs HAS-A Relationships — Java Interview Q&A

All Java topics

How inheritance models what a class is versus composition models what a class contains. Part of OOP Mechanics · 294 questions in the Java bank.

What is an IS-A relationship in Java?

Answer

An IS-A relationship models inheritance, where a subclass is a specialized kind of its superclass and reuses its code. In Java you express it with extends for classes and implements for interfaces, so a Car that extends Vehicle can be treated as a Vehicle. The benefit is reuse plus polymorphism, because common state and behavior live once in the parent.

Key points

  1. 1Motorcycle is a Vehicle and Car is a Vehicle are classic examples.
  2. 2Subclass objects can be assigned to superclass references for polymorphism.
  3. 3Common fields and methods are written once in the parent and inherited.

Example

Example.javajava
class Vehicle { void move() {} }
class Car extends Vehicle { int seats; }

💡 If the sentence X is a Y sounds wrong, inheritance is the wrong tool.

What is a HAS-A relationship in Java?

Answer

A HAS-A relationship models composition or aggregation, where one object holds a reference to another object as a field. There is no special keyword for it: you declare a field of the part type and initialize it with new or receive it through a constructor. It also promotes reuse, and it is often preferred over inheritance because the container uses the part without inheriting its full identity.

Key points

  1. 1Implemented with a field reference, not with extends.
  2. 2Models part and whole, such as an Engine inside a Car.
  3. 3Favors composition because the container delegates instead of inheriting.

Example

Example.javajava
class Engine { void start() {} }
class Car { private Engine engine = new Engine(); }

What is the difference between IS-A and HAS-A?

Answer

IS-A means one type is a subtype of another, while HAS-A means one object contains another object as a part. You write IS-A with extends or implements, as in Car is a Vehicle, and you write HAS-A with a field reference, as in Car has an Engine. Use inheritance when substitutability makes sense, and use composition when you only need behavior without adopting a new identity.

Key points

  1. 1IS-A uses extends or implements and supports polymorphism through substitution.
  2. 2HAS-A uses a field reference and supports reuse through delegation.
  3. 3Favor composition when the part can change independently of the whole.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits