+ 1
What is composition in java? And how it is different from inheritance? Help me out
3 Réponses
+ 4
Composition means HAS A
Inheritance means IS A
Example: Car has a Engine and Car is a Automobile
In programming this is represented as:
class Engine {} // The engine class.
class Automobile{} // Automobile class which is parent to Car class.
// Car is an Automobile, so Car class extends Automobile class.
class Car extends Automobile{
// Car has a Engine so, Car class has an instance of Engine class as its member.
private Engine engine;
}
+ 2
Well, Composition is the OOP concept, where an object appears as a member in other class.
Example
class address {
String city;
int id;
}
class person {
int id;
String name;
address add; //Composition
}
On there other hand, inheritance allows creating new class on basis of existing class to add new functionality.
//base class
class Point {
int x;
int y;
....
}
class Point3d extends Point {
int z; //
}
Here class Point3d will receive all public and protected members of Point class and will have additional members of its own.
+ 1
thanx it helps😊