I have 4 classes : "stones", "seaweed", "sprats" and "pikes", each successive class inherits the properties of the previous one.
Class "stones" have the coordinates, a class "seaweed" added to the coordinates the lifetime and the rate of growth, as well as the birth of a new seaweed (division of old), in "sprats" added method of eating seaweed.
Should I use normal java classes to express such inheritance or is there another way for such inheritance?
In such a case when semantically there is no real relation between the two objects I would discourage directly using class inheritance.
If you wish to express the fact that these classes have certain aspects of their behaviour in common, you might want to use interfaces which express these sets of properties. This works because a class can implement multiple interfaces, so you can pick and choose which to implement in each class. This also introduces greater flexibility since a linear ordering of the different, not strictly related functionalities is not necessary.
Example: You could have
public interface WorldObject {...}
public interface Organism extends WorldObject {...}
public interface Plant extends Organism {...}
public interface Animal extends Organism {...}
public interface Eater<T> {...}
public class Stone implements WorldObject {...}
public class Seaweed implements Plant {...}
public class Sprat implements Animal, Eater<Seaweed> {...}
etc.
Composition is good alternative to inheritance.
So you will have additional classes such as Coordinates, LifeStyle, Consumer
and define your classes
class Stone{
Coordinates coordinates;
}
class Seaweed{
Coordinates coordinates;
LifeStyle lifestyle;
}
class Sprats{
Coordinates coordinates;
LifeStyle lifestyle;
List<Consumer<?>> consumers;
}
is it better alternative than inheritance, it depends on your project.
Related
abstract class CAR
fuelUp () { // implemented }
/ \
interface SPORTER interface TRUCK
driveFast (); moveLoad ();
Is there a way in Java I can get
a class ESTATE that has
the implementation fuelUp of CAR
and also must implement driveFast AND moveLoad?
Extending from multiple classes is not possible and making CAR an interface does not give me an implementation in CAR.
Your Java class can only extend 1 parent class, but it can implement multiple interfaces
Your class definition would be as follows:
class ESTATE extends CAR implements SPORTER, TRUCK {}
For more help, see:
https://stackoverflow.com/a/21263662/4889267
As already identified, you can extend one class and implement multiple interfaces. And in Java 8+, those interfaces can have default implementations.
But to add to this, you can also have various implementations of SPORTER, for instance. You could make use of the SporterAlpha implementation through composition.
class Foo extends Car implements Sporter {
private SporterAlpha sporterAlpha;
public int sporterMethodA(int arg1) { return sporterAlpha.sporterMethodA(arg1); }
}
Repeat as necessary to expose all the SporterAlpha methods necessary.
Thus, you can:
Inherit from no more than one superclass
Implement as many interfaces as necessary
Use default implementations on your interfaces with Java 8+
Use composition as appropriate
What is the type of a class if it implements more than one interface?
For example if the class Example implements Interface1 doesExample become of type Interface1? If so what happens if it also implements Interface2. What type is class Example then?
The phrase "become of type interface1" is not clear.
In OO design, a class is supposed to represent a particular "object" or "thing" in your problem domain. If you're writing a system to model vehicles on highways, you might have classes (or interfaces) for "vehicle", "road", etc.
Let's say a part of the system also dealt with commercial vehicles; taxes or something. So there might be a class of "vehicle" and an interface of "CommercialVehicle", with the latter providing methods to get attributes connected with road taxes for the vehicle. Not all Vehicles would be CommercialVehicles, but some of them would implement that interface.
An object of type Vehicle might or might not implement that interface. IF it does implement the interface, that guarantees that it has the associated methods. You can use the "instanceof" operator to determine whether a particular object implements an interface or not.
But I'm not sure what you mean by "become of type interface", so I'm not sure how to answer that question.
Implementing is for interfaces. Extending is for classes.
In Java, you can implement many interfaces, but extend only one.
If you extend a class, you don't become anything, but you do inherit its members (fields, methods, subclasses).
As per your (vague) question, let's assume:
public interface Interface1 {
void myMethod(Interface1 other); // using public is redundant in interfaces
}
public class Example implements Interface1, Interface2 { ... }
Then Example is of type Example (...), and when I need to implement the methods in the interface then:
public void myMethod(Interface1 myObject) {
Example myClass = (Example)myObject;
}
I need to cast to use the methods from Example.
I want to have a Class object, but I want to force whatever class it represents to extend class A and also class B.
I can do
<T extends ClassA & ClassB>
but it is not possible to extend from both classes, Is there a way to do this?
In java you cannot have a class which extends from two classes, since it doesn't support multiple inheritance. What you can have, is something like so:
public class A
...
public class B extends A
...
public class C extends B
...
In your generic signature, you can then specify that T must extend C: <T extends C>.
You could give a look at Default Methods (if you are working with Java 8), which essentially are methods declared within interfaces, and in Java, a class can implement multiple interfaces.
A simple way for this problem is inheritance.
public class A { // some codes }
public class B extends A { }
<T extends A>
Java does not have multiple inheritance as a design decision, but you may implement multiple interfaces.
As of Java 8 these interfaces may have implementations.
To use multiple classes there are other patterns:
If the parent classes are purely intended for that child class, but handle entirely different aspects, and were therefore separated, place them in a single artificial hierarchy. I admit to doing this once.
Use delegation; duplicate the API and delegate.
Use a lookup/discovery mechanism for very dynamic behaviour.
public T lookup(Class klazz);
This would need an API change, but uncouples classes, and is dynamic.
I'm having trouble understanding when to use an interface as opposed to an abstract class and vice versa. Also, I am confused when to extend an interface with another interface. Sorry about the long post, but this is very confusing.
Creating shapes seems like a popular starting point. Let's say we want a way to model 2D shapes. We know that each shape will have an area. What would be the difference between the following two implementations:
with interfaces:
public interface Shape {
public double area();
}
public class Square implements Shape{
private int length = 5;
public Square(){...}
public double area()
return length * length;
}
}
with abstract class:
abstract class Shape {
abstract public double area();
}
public class Square extends Shape {
private length = 5;
public Square(){...}
public double area(){
return length * length;
}
I understand that abstract classes allows you to define instance variables and allows you to give method implementations whereas an interface cannot do these things. But in this case, it seems like these two implementations are identical. So using any one is fine?
But now say we want to describe different types of triangles. We can have an isosceles, acute, and right angle triangles. To me, it makes sense to use class inheritance in this case. Using the 'IS-A' definition: a Right Triangle "IS-A" Triangle. A Triangle "IS-A" Shape. Also, an abstract class should define behaviors and attributes that are common within all subclasses, so this is perfect:
with abstract class
abstract Triangle extends Shape {
private final int sides = 3;
}
class RightTriangle extends Triangle {
private int base = 4;
private int height = 5;
public RightTriangle(){...}
public double area() {
return .5 * base * height
}
}
We can do this with interfaces as well, with Triangle and Shape being interfaces. However, unlike class inheritance (using 'IS-A' relationship to define what should be a subclass), I'm not sure how to use an interface. I see two ways:
First way:
public interface Triangle {
public final int sides = 3;
}
public class RightTriangle implements Triangle, Shape {
private int base = 4;
private int height = 5;
public RightTriangle(){}
public double area(){
return .5 * height * base;
}
}
Second way:
public interface Triangle extends Shape {
public final int sides = 3;
}
public class RightTriangle implements Triangle {
....
public double area(){
return .5 * height * base;
}
}
It seems to me like both of these ways work. But when would you use one way over the other? And are there any advantages to using interfaces over abstract classes to represent different triangles? Even though we complicated the description of a shape, using interface vs abstract class still seem equivalent.
A critical component to interfaces is that it can define behaviors that can be shared across unrelated classes. So an interface Flyable would be present in classes Airplane as well as in Bird. So in this case, it is clear that an interface approach is preferred.
Also, to build off of the confusing interface extending another interface:
When should the 'IS-A' relationship be ignored when deciding on what should be an interface?
Take this example: LINK.
Why should 'VeryBadVampire' be a class and 'Vampire' be an interface? A 'VeryBadVampire' IS-A 'Vampire', so my understanding is that a 'Vampire' should be a superclass (maybe abstract class). A 'Vampire' class can implement 'Lethal' to keep its lethal behavior. Furthermore, a 'Vampire' IS-A 'Monster', so 'Monster' should be a class as well. A 'Vampire' class can also implement an interface called 'Dangerous' to keep its dangerous behavior. If we wish to create a new monster called 'BigRat' which is dangerous but not lethal, then we can create a 'BigRat' class which extends 'Monster' and implements 'Dangerous'.
Wouldn't the above achieve the same output as using 'Vampire' as an interface (described in the link)? The only difference I see is that using class inheritance and preserving the 'IS-A' relationship clears up a lot of confusion. Yet this is not followed. What is the advantage of doing this?
Even if you wanted a monster to share vampiric behavior, one can always redefine how the objects are represented. If we wanted a new type of vampire monster called 'VeryMildVampire' and we wanted to create a vampire-like monster called 'Chupacabra', we can do this:
'Vampire' class extends 'Monster' implements 'Dangerous', 'Lethal', 'BloodSuckable'
'VeryMildVampire' class extends 'Vampire' class
'Chupacabra' class extends 'Monster' implements 'BloodSuckable'
But we can also do this:
'VeryMildVampire' extends 'Monster' implements Dangerous, Lethal, Vampiric
'Chupacabra' extends 'Monster' implements Dangerous, Vampiric
The second way here creates a 'Vampiric' interface so that we can more easily define a related monster rather than create a bunch of interfaces which define vampiric behaviors (like in the first example). But this breaks the IS-A relationship. So I'm confused...
Remember the basic concept when using abstract classes or interfaces.
Abstract classes are used when class to extended is more closely coupled to the class implementing it, i.e when both have a parent-child relation.
In example:
abstract class Dog {}
class Breed1 extends Dog {}
class Breed2 extends Dog {}
Breed1 and Breed2 are both types of a dog and has some common behavior as a dog.
Whereas, an interface is used when implementing class has a feature it can take from the class to implemented.
interface Animal {
void eat();
void noise();
}
class Tiger implements Animal {}
class Dog implements Animal {}
Tiger and Dog are two different category but both eat and make noises ,which are different. So they can use eat and noise from Animal.
Use an abstract class when you want to make one or more methods not abstract.
If you want to keep all abstract, use an interface.
This is question that will come to when designing class hierarchies that are bit complicated that normal. But generally there are few things you need to know when using abstract classes and interfaces
Abstract Class
Allows you to leverage the power of using constructors and constructor overriding
Restrict the class having multiple inheritance(This is particularly useful if you are designing a complicated API)
Instance variables and method implementations
Leverage the power of method super calling(Use super to call the parent abstract class's implementation)
Interface
Enables multiple inheritance - you can implement n number of interfaces
Allows to represent only conceptual methods (No method bodies)
Generally use Interfaces for '-able' clause(as in functionality).
Eg:-
Runnable
Observable
Use abstract classes for something like is-a(evolution format).
Eg:-
Number
Graphics
But hard and fast rules are not easy to create. Hope this helps
You have quite a few questions here. But I think basically you are asking about interface vs. abstract class.
With interfaces, you can have classes that implement multiple interfaces. However, interface is not durable if you want to use it as the API. Once the interface is published, it's hard to modify the interface because it will break other people's codes.
With abstract class, you can only extends one class. However, abstract class is durable for API because you can still modify in later versions without breaking other people's code. Also with abstract class, you can have predefined implementation. For example, in your Triangle example, for abstract class, you may have a method countEdges() which returns 3 by default.
This is a question that comes up very often, yet there is no single "right" answer that will please everyone.
Classes represent is-a relationships and interfaces represent can-do behaviour. I usually go by a few empirical rules:
Stick with a class (abstract/concrete) unless you are certain that you need an interface.
If you do use interfaces, slice them into very specific functionality. If an interface contains more than a few methods, you're doing it wrong.
Further, most examples of shapes and persons (or vampires for that matter!) are usually poor examples of real-world models. The "right" answer depends on what your application requires. For instance, you mentioned:
class Vampire extends Monster implements Dangerous, Lethal, BloodSuckable
Does your application really need all these interfaces? How many different types of Monsters are there? Do you actually have classes other than Vampire that implement BloodSuckable?
Try not to generalize too much and extract interfaces when you have no need for them. This goes back to the rule of thumb: stick with a simple class unless your use case demands an interface.
This is a good question. There are many good and bad answers for this question. Typical question is, what is the difference between an abstract class an interface? Lets see where you use abstract classes and where you use interface.
Where to use abstract classes:
In terms of OOP, If there is an inheritance hierarchy then you should use an abstract class to model your design.
Where to use interfaces:
When you have to connect different contracts(non related classes) using one common contract then you should use an interface. Lets take Collection framework as an example.
Queue,List,Set have different structures from their implementation.But still they share some common behaviors like add(),remove(). So we can create an interface called Collection and the we have declared common behaviors in the interface. As you see, ArrayList implements all the behaviors from both List and RandomAccess interfaces.Doing so we can easily add new contracts without changing the existing logic. This is called as "coding to an interface".
Your shape example is good. I look at it this way:
You only have abstract classes when you have methods or member variables that are shared. For your example for Shape you've only got a single, unimplemented method. In that case always use an interface.
Say you had an Animal class. Each Animal keeps track of how many limbs it has.
public abstract class Animal
{
private int limbs;
public Animal(int limbs)
{
this.limbs = limbs;
}
public int getLimbCount()
{
return this.limbs;
}
public abstract String makeNoise();
}
Because we need to keep track of how many limbs each animal has, it makes sense to have the member variable in the superclass. But each animal makes a different type of noise.
So we need to make it an abstract class as we have member variables and implemented methods as well as abstract methods.
For your second question, you need to ask yourself this.
Is a Triangle always going to be a shape?
If so, you need to have Triangle extend from the Shape interface.
So in conclusion - with your first set of code examples, choose the interface. With the last set, choose the second way.
Are Composition and Inheritance the same?
If I want to implement the composition pattern, how can I do that in Java?
They are absolutely different. Inheritance is an "is-a" relationship. Composition is a "has-a".
You do composition by having an instance of another class C as a field of your class, instead of extending C. A good example where composition would've been a lot better than inheritance is java.util.Stack, which currently extends java.util.Vector. This is now considered a blunder. A stack "is-NOT-a" vector; you should not be allowed to insert and remove elements arbitrarily. It should've been composition instead.
Unfortunately it's too late to rectify this design mistake, since changing the inheritance hierarchy now would break compatibility with existing code. Had Stack used composition instead of inheritance, it can always be modified to use another data structure without violating the API.
I highly recommend Josh Bloch's book Effective Java 2nd Edition
Item 16: Favor composition over inheritance
Item 17: Design and document for inheritance or else prohibit it
Good object-oriented design is not about liberally extending existing classes. Your first instinct should be to compose instead.
See also:
Composition versus Inheritance: A Comparative Look at Two Fundamental Ways to Relate Classes
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.
class Car extends Automobile { // Car is an Automobile, so Car class extends Automobile class.
private Engine engine; // Car has an Engine so, Car class has an instance of Engine class as its member.
}
How inheritance can be dangerous ?
Lets take an example
public class X{
public void do(){
}
}
Public Class Y extends X{
public void work(){
do();
}
}
1) As clear in above code , Class Y has very strong coupling with class X. If anything changes in superclass X , Y may break dramatically. Suppose In future class X implements a method work with below signature
public int work(){
}
Change is done in class X but it will make class Y uncompilable. SO this kind of dependency can go up to any level and it can be very dangerous. Every time superclass might not have full visibility to code inside all its subclasses and subclass may be keep noticing what is happening in superclass all the time. So we need to avoid this strong and unnecessary coupling.
How does composition solves this issue?
Lets see by revising the same example
public class X{
public void do(){
}
}
Public Class Y{
X x = new X();
public void work(){
x.do();
}
}
Here we are creating reference of X class in Y class and invoking method of X class by creating an instance of X class.
Now all that strong coupling is gone. Superclass and subclass are highly independent of each other now. Classes can freely make changes which were dangerous in inheritance situation.
2) Second very good advantage of composition in that It provides method calling flexibility, for example :
class X implements R
{}
class Y implements R
{}
public class Test{
R r;
}
In Test class using r reference I can invoke methods of X class as well as Y class. This flexibility was never there in inheritance
3) Another great advantage : Unit testing
public class X {
public void do(){
}
}
Public Class Y {
X x = new X();
public void work(){
x.do();
}
}
In above example, if state of x instance is not known, it can easily be mocked up by using some test data and all methods can be easily tested. This was not possible at all in inheritance as you were heavily dependent on superclass to get the state of instance and execute any method.
4) Another good reason why we should avoid inheritance is that Java does not support multiple inheritance.
Lets take an example to understand this :
Public class Transaction {
Banking b;
public static void main(String a[])
{
b = new Deposit();
if(b.deposit()){
b = new Credit();
c.credit();
}
}
}
Good to know :
composition is easily achieved at runtime while inheritance provides its features at compile time
composition is also know as HAS-A relation and inheritance is also known as IS-A relation
So make it a habit of always preferring composition over inheritance for various above reasons.
The answer given by #Michael Rodrigues is not correct (I apologize; I'm not able to comment directly), and could lead to some confusion.
Interface implementation is a form of inheritance... when you implement an interface, you're not only inheriting all the constants, you are committing your object to be of the type specified by the interface; it's still an "is-a" relationship. If a car implements Fillable, the car "is-a" Fillable, and can be used in your code wherever you would use a Fillable.
Composition is fundamentally different from inheritance. When you use composition, you are (as the other answers note) making a "has-a" relationship between two objects, as opposed to the "is-a" relationship that you make when you use inheritance.
So, from the car examples in the other questions, if I wanted to say that a car "has-a" gas tank, I would use composition, as follows:
public class Car {
private GasTank myCarsGasTank;
}
Hopefully that clears up any misunderstanding.
Inheritance brings out IS-A relation. Composition brings out HAS-A relation.
Strategy pattern explain that Composition should be used in cases where there are families of algorithms defining a particular behaviour.Classic example being of a duck class which implements a flying behaviour.
public interface Flyable{
public void fly();
}
public class Duck {
Flyable fly;
public Duck(){
fly = new BackwardFlying();
}
}
Thus we can have multiple classes which implement flying
eg:
public class BackwardFlying implements Flyable{
public void fly(){
Systemout.println("Flies backward ");
}
}
public class FastFlying implements Flyable{
public void fly(){
Systemout.println("Flies 100 miles/sec");
}
}
Had it been for inheritance, we would have two different classes of birds which implement the fly function over and over again. So inheritance and composition are completely different.
Composition is just as it sounds - you create an object by plugging in parts.
EDIT the rest of this answer is erroneously based on the following premise.
This is accomplished with Interfaces.
For example, using the Car example above,
Car implements iDrivable, iUsesFuel, iProtectsOccupants
Motorbike implements iDrivable, iUsesFuel, iShortcutThroughTraffic
House implements iProtectsOccupants
Generator implements iUsesFuel
So with a few standard theoretical components you can build up your object. It's then your job to fill in how a House protects its occupants, and how a Car protects its occupants.
Inheritance is like the other way around. You start off with a complete (or semi-complete) object and you replace or Override the various bits you want to change.
For example, MotorVehicle may come with a Fuelable method and Drive method. You may leave the Fuel method as it is because it's the same to fill up a motorbike and a car, but you may override the Drive method because the Motorbike drives very differently to a Car.
With inheritance, some classes are completely implemented already, and others have methods that you are forced to override. With Composition nothing's given to you. (but you can Implement the interfaces by calling methods in other classes if you happen to have something laying around).
Composition is seen as more flexible, because if you have a method such as iUsesFuel, you can have a method somewhere else (another class, another project) that just worries about dealing with objects that can be fueled, regardless of whether it's a car, boat, stove, barbecue, etc. Interfaces mandate that classes that say they implement that interface actually have the methods that that interface is all about. For example,
iFuelable Interface:
void AddSomeFuel()
void UseSomeFuel()
int percentageFull()
then you can have a method somewhere else
private void FillHerUp(iFuelable : objectToFill) {
Do while (objectToFill.percentageFull() <= 100) {
objectToFill.AddSomeFuel();
}
Strange example, but it's shows that this method doesn't care what it's filling up, because the object implements iUsesFuel, it can be filled. End of story.
If you used Inheritance instead, you would need different FillHerUp methods to deal with MotorVehicles and Barbecues, unless you had some rather weird "ObjectThatUsesFuel" base object from which to inherit.
Are Composition and Inheritance the same?
They are not same.
Composition : It enables a group of objects have to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies
Inheritance: A class inherits fields and methods from all its superclasses, whether direct or indirect. A subclass can override methods that it inherits, or it can hide fields or methods that it inherits.
If I want to implement the composition pattern, how can I do that in Java?
Wikipedia article is good enough to implement composite pattern in java.
Key Participants:
Component:
Is the abstraction for all components, including composite ones
Declares the interface for objects in the composition
Leaf:
Represents leaf objects in the composition
Implements all Component methods
Composite:
Represents a composite Component (component having children)
Implements methods to manipulate children
Implements all Component methods, generally by delegating them to its children
Code example to understand Composite pattern:
import java.util.List;
import java.util.ArrayList;
interface Part{
public double getPrice();
public String getName();
}
class Engine implements Part{
String name;
double price;
public Engine(String name,double price){
this.name = name;
this.price = price;
}
public double getPrice(){
return price;
}
public String getName(){
return name;
}
}
class Trunk implements Part{
String name;
double price;
public Trunk(String name,double price){
this.name = name;
this.price = price;
}
public double getPrice(){
return price;
}
public String getName(){
return name;
}
}
class Body implements Part{
String name;
double price;
public Body(String name,double price){
this.name = name;
this.price = price;
}
public double getPrice(){
return price;
}
public String getName(){
return name;
}
}
class Car implements Part{
List<Part> parts;
String name;
public Car(String name){
this.name = name;
parts = new ArrayList<Part>();
}
public void addPart(Part part){
parts.add(part);
}
public String getName(){
return name;
}
public String getPartNames(){
StringBuilder sb = new StringBuilder();
for ( Part part: parts){
sb.append(part.getName()).append(" ");
}
return sb.toString();
}
public double getPrice(){
double price = 0;
for ( Part part: parts){
price += part.getPrice();
}
return price;
}
}
public class CompositeDemo{
public static void main(String args[]){
Part engine = new Engine("DiselEngine",15000);
Part trunk = new Trunk("Trunk",10000);
Part body = new Body("Body",12000);
Car car = new Car("Innova");
car.addPart(engine);
car.addPart(trunk);
car.addPart(body);
double price = car.getPrice();
System.out.println("Car name:"+car.getName());
System.out.println("Car parts:"+car.getPartNames());
System.out.println("Car price:"+car.getPrice());
}
}
output:
Car name:Innova
Car parts:DiselEngine Trunk Body
Car price:37000.0
Explanation:
Part is a leaf
Car contains many Parts
Different Parts of the car have been added to Car
The price of Car = sum of ( Price of each Part )
Refer to below question for Pros and Cons of Composition and Inheritance.
Prefer composition over inheritance?
as another example, consider a car class, this would be a good use of composition, a car would "have" an engine, a transmission, tires, seats, etc. It would not extend any of those classes.
Composition is where something is made up of distinct parts and it has a strong relationship with those parts. If the main part dies so do the others, they cannot have a life of their own. A rough example is the human body. Take out the heart and all the other parts die away.
Inheritance is where you just take something that already exists and use it. There is no strong relationship. A person could inherit his fathers estate but he can do without it.
I don't know Java so I cannot provide an example but I can provide an explanation of the concepts.
In Simple Word Aggregation means Has A Relationship ..
Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.
Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.
Why Use Aggregation
Code Reusability
When Use Aggregation
Code reuse is also best achieved by aggregation when there is no is a Relation ship
Inheritance
Inheritance is a Parent Child Relationship Inheritance Means Is A RelationShip
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.
Using inheritance in Java
1 Code Reusability.
2 Add Extra Feature in Child Class as well as Method Overriding (so runtime polymorphism can be achieved).
Inheritance between two classes, where one class extends another class establishes "IS A" relationship.
Composition on the other end contains an instance of another class in your class establishes "Has A" relationship. Composition in java is is useful since it technically facilitates multiple inheritance.
Though both Inheritance and Composition provides code reusablility, main difference between Composition and Inheritance in Java is that Composition allows reuse of code without extending it but for Inheritance you must extend the class for any reuse of code or functionality. Another difference which comes from this fact is that by using Composition you can reuse code for even final class which is not extensible but Inheritance cannot reuse code in such cases. Also by using Composition you can reuse code from many classes as they are declared as just a member variable, but with Inheritance you can reuse code form just one class because in Java you can only extend one class, because multiple Inheritance is not supported in Java. You can do this in C++ though because there one class can extend more than one class. BTW, You should always prefer Composition over Inheritance in Java, its not just me but even Joshua Bloch has suggested in his book
I think this example explains clearly the differences between inheritance and composition.
In this exmple, the problem is solved using inheritance and composition. The author pays attention to the fact that ; in inheritance, a change in superclass might cause problems in derived class, that inherit it.
There you can also see the difference in representation when you use a UML for inheritance or composition.
http://www.javaworld.com/article/2076814/core-java/inheritance-versus-composition--which-one-should-you-choose-.html
Inheritances Vs Composition.
Inheritances and composition both are used to re-usability and extension of class behavior.
Inheritances mainly use in a family algorithm programming model such as IS-A relation type means similar kind of object. Example.
Duster is a Car
Safari is a Car
These are belongs to Car family.
Composition represents HAS-A relationship Type.It shows the ability of an object such as Duster has Five Gears , Safari has four Gears etc. Whenever we need to extend the ability of an existing class then use composition.Example we need to add one more gear in Duster object then we have to create one more gear object and compose it to the duster object.
We should not make the changes in base class until/unless all the derived classes needed those functionality.For this scenario we should use Composition.Such as
class A Derived by Class B
Class A Derived by Class C
Class A Derived by Class D.
When we add any functionality in class A then it is available to all sub classes even when Class C and D don't required those functionality.For this scenario we need to create a separate class for those functionality and compose it to the required class(here is class B).
Below is the example:
// This is a base class
public abstract class Car
{
//Define prototype
public abstract void color();
public void Gear() {
Console.WriteLine("Car has a four Gear");
}
}
// Here is the use of inheritence
// This Desire class have four gears.
// But we need to add one more gear that is Neutral gear.
public class Desire : Car
{
Neutral obj = null;
public Desire()
{
// Here we are incorporating neutral gear(It is the use of composition).
// Now this class would have five gear.
obj = new Neutral();
obj.NeutralGear();
}
public override void color()
{
Console.WriteLine("This is a white color car");
}
}
// This Safari class have four gears and it is not required the neutral
// gear and hence we don't need to compose here.
public class Safari :Car{
public Safari()
{ }
public override void color()
{
Console.WriteLine("This is a red color car");
}
}
// This class represents the neutral gear and it would be used as a composition.
public class Neutral {
public void NeutralGear() {
Console.WriteLine("This is a Neutral Gear");
}
}
Composition means creating an object to a class which has relation with that particular class.
Suppose Student has relation with Accounts;
An Inheritance is, this is the previous class with the extended feature. That means this new class is the Old class with some extended feature.
Suppose Student is Student but All Students are Human. So there is a relationship with student and human. This is Inheritance.
Inheritence means reusing the complete functionality of a class, Here my class have to use all the methods of the super class and my class will be titely coupled with the super class and code will be duplicated in both the classes in case of inheritence.
But we can overcome from all these problem when we use composition to talk with another class . composition is declaring an attribute of another class into my class to which we want to talk. and what functionality we want from that class we can get by using that attribute.
No , Both are different . Composition follow "HAS-A" relationship and inheritance follow "IS-A" relationship . Best Example for composition was Strategic pattern .