Junior
What do the relationships "is-a" and "has" mean in object-oriented programming?
sobes.tech AI
Answer from AI
The "is-a" relationship — inheritance. A subclass "is" a superclass and inherits its properties and behavior.
// Superclass
class Animal {
void eat() {
System.out.println("Animal eats");
}
}
// Subclass
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
In this example, Dog "is a" Animal.
The "has-a" relationship — composition or aggregation. One object "has" a reference to another object as part of its state.
class Engine {
void start() {
System.out.println("Engine started");
}
}
class Car {
private Engine engine; // Car "has" an engine
public Car() {
this.engine = new Engine();
}
void drive() {
engine.start();
System.out.println("Car is driving");
}
}
Here, Car "has" an Engine. Composition implies a strong relationship (the lifecycle of the contained object depends on the container), while aggregation is a weaker relationship (objects can exist independently). The example shows composition.
Key difference:
- "Is-a" (
is-a) — inheritance, defines a type hierarchy. - "Has-a" (
has-a) — composition/aggregation, defines the structure of an object through inclusion of other objects.