I want to implement a model checker for Java class diagrams.
There are many constraints that I've been considered for a while.
Hope anyone can help me figure it out.
All the cycles here I mean are pure cycles with only one type of relationship.
Q1: Suppose class A is composed of class B, is it possible that class B is also composed of class A, given that class A and class B are different classes? Moreover, is it possible for composition relationship to have cycles?
Q2: What about other relationship in the class diagram, like aggregation, dependence and association? What's the meaning of cycles in these relationships? Can anyone give some examples?
Thanks for reading my question and hope someone can help me out.
Q1: Suppose class A is composed of class B, is it possible that class
B is also composed of class A, given that class A and class B are
different classes? Moreover, is it possible for composition
relationship to have cycles?
Strictly speaking in UML terms... yes, but you'd be hard pressed to actually implement this in code. If you ask yourself, "can B stand alone without A?" and "can A stand alone without B?" If you can answer no to both of those at the same time, then you can have two classes composed of each other. Since one would have to be able to stand on its own for the other to be composed of it, you can't have both. However, since composition vs aggregation is largely based on design and context, it's not completely impossible. You can for instance, have something like this:
Class B contains a reference to A, and A contains a reference to B
public class A {
B myB;
String name = "A";
public A(int num) {
this.name += num;
}
public void setMyB(B b) {
this.myB = b;
}
public B getMyB() {
return this.myB;
}
public String getName() {
return this.name;
}
}
public class B {
A myA;
String name = "B";
public B(int num) {
this.name += num;
myA = new A(num);
}
public A getMyA() {
return this.myA;
}
public String getName() {
return this.name;
}
}
In this example, we provide an identifier for the class using a defined String and then append a number to it, just to show some unique ID.
We provide methods that allow us to access both A and B references, but only B creates its reference to the other via the constructor (composition).
Using this simple test:
public class Test {
public static void main(String[] args) {
A myA = new A(1);
B myB = new B(2);
B anotherB = new B(3);
myA.setMyB(anotherB);
System.out.println("A = " + myA.getName());
System.out.println("A's B = " + myA.getMyB().getName());
System.out.println("B = " + myB.getName());
System.out.println("B'a A = " + myB.getMyA().getName());
}
}
We can see the following output
A = A1
A's B = B3
B = B2
B'a A = A2
In this example, the B reference in A is created outside the context of A and passed in as an argument. If we deleted myB, we'd lose the reference to its A, but not if we deleted myA (we still have anotherB.
Suppose we eliminated the setMyB() method from A and moved it to the constructor... we'd have an infinite loop of new objects and you'd end up with a StackOverflowError
You could probably get creative and try to implement the Singleton pattern or some other construct that limits the number of objects created, but doing so would mean the constructors would need to be private/hidden, which prevents extension by other classes. Use of a static field to track number of creations might prevent the error, but then you'd lose all the references without having a place to keep track of them all, and lastly, you'd never have a "perfect" composition, because one class would be missing its component.
After all this "analysis" you'd end up coming up with a design that makes sense, not one that strictly fits what's drawn on a UML diagram. The UML diagram is there to convey "relationships" between classes. The "unique" case you've asked about here where A uses B and B uses A is probably not going to be solved with UML modeling, but probably needs some other design work.
Q2: What about other relationship in the class diagram, like
aggregation, dependence and association? What's the meaning of cycles
in these relationships? Can anyone give some examples?
Association relationships are really used to describe the type of relationships that are defined by composition, aggregation, many-to-many, one-to-one etc, and depend on the context. The meaning of cycles in every association is going to depend on your design.
In general, a cycle in a dependency means that the class depends on itself. This could be for recursive function calling, Singleton design pattern implementation, or some other design pattern requiring a class to refer to itself.
Aggregation was sort of already answered above. It basically means the object "uses" whatever it's aggregating. An example is a Company aggregates People. When the company goes away, the people still exist. A cycle in that kind of relationship is similar to what was shown in my example, except you'd have external references to both A and B classes that were passed as arguments to the first two references to A and B.
The bottom line is... UML is a tool to show relationships between classes. The design and implementation will follow from that and the fact that you have "interesting" relationships modeled with UML will not help you get past serious design roadblocks.
Hopefully this helps shed some light on your questions.
Related
I have 3 different JAVA classes named as A, B, C . All these classes contain either each other's reference object or a list of objects. My main aim is to combine all these classes into one single JAVA class (A). Please find below the structure:
public class A {
private B b;
...
}
public class B {
private List<C> c;
...
}
public class C{
private TreeMap<int, int> t;
...
}
Since I am new to JAVA , I am not sure how would I combine these together into one single class 'A'? Experts please help me in this case.
Here's the class combined [single Java class (A)]:
public class A {
private A b;
private List<A> c;
private TreeMap<Integer, Integer> t
...
}
Now, for a little OOP best practices rant. You need to think of each class as having a single responsibility (single responsibility principle). If you say, "this class does this and that". Then it has too many responsibilities. The key word is "and". It implies multiple responsibilities. If you can safely say, each one of these classes share a single responsibility, then I guess it's okay to join them together. However, I'm doubting this is the case. It seems to make more since to keep them split.
First of all, your code will not compile, we don't use TreeMap<int, int>, colections only use Objects, it's Javadocs:
A collection represents a group of objects, known as its elements.
Otherwise. your code seems to be good enough, regarding your comment:
simple exercises with JAVA collections and finding out the best
practices for the same. This problem seems to be list of maps but I
want to know whether that is the most optimized way of doing it or
not?
your question has nothing to do with optimized use of collections, but if you are not willing to use class B and class C in other classes, then you can use inner classes like this:
class A {
private B b;
class B {
private List<C> c;
....
}
class C {
private TreeMap<Integer, Integer> t;
....
}
}
More informations about how use inner classes, could be found here.
I have two questions to ask. So let's assume there's a class A and B which are defined like these.
1.
class A {
private B b;
private B otherB;
public A(B otherB)
{
this.otherB = otherB;
}
}
class B {
}
So class A has a composition relationship with the variable b and aggregation relationship with the variable otherB. How can I draw this in UML diagram.
2.Would the following case be still a composition relationship?
class A
{
private B b;
public B getMethod(){
B newB = new B();
newB.bValue = b.bValue;
return newB;
}
}
class B
{
private int bValue;
}
As other comments/replies have pointed out, there is not problem of having different associations (composed or not) between the same classes.
From the implementation point of view (and this also applies to the previous question) you need to understand what a composition association means.
Basically, if we have instance specification a1 and a2 (as instances of the class A), only one of them could compose an instance b1 (as instance of the class B) via the role (association end) "composesB" of the composite association.
Likewise, provided that a1 composes b1 via the "composesB" role of a composite association, everytime a1 gets "destroyed", b1 should also be "destroyed". Instead, this wouldn´t occur if a1 object aggregated b1 via the "aggregatesB" role of an aggregate association.
As you may imagine, from an implementation point of view, you need much more than a field and a simple method in a class in order to support a composite association between two classes.
Update: to include an example.
For example, EMF is an implementation of the EMOF specification (it´s not UML) in which the concept of a containment reference (similar to the concept of a composite association) can be depicted as follows. In our particular case:
Going away from technical details, you may grasp that when you set a B instance as part (contained, composed) by an A instance object. You firstly have to check that the former might be contained in a different A instance via the same containment reference, if so, such B instance needs to be removed from the old A instance one.
Creating Multiple Associations Between Classes is, in fact, legal. The recommendation is to assign a role to each relationship when you do so.
I'm going to say yes, that is still a composition relationship (though others may disagree). To make my case, we look at the simple IBM definition showing Student composed of Schedule (presumably amongst other things). It's very easy to imagine that there would also be a Teacher composed of Schedule, and that a Teacher might want to get the Schedule of a Student, or vice versa. Does the getting of a Schedule by another class invalidate the composition relationship? I think not; or at least, the IBM definition does not appear to be so narrow as to preclude that possibility.
I have two parent classes in a huge project, let's say ClassA and ClassB. Each class has many subclasses, which in turn have many subclasses, which in turn have many subclasses, etc.
My task is to "marry" these two "families" so that both inherit from a SINGLE parent. I need to essentially make ClassA and ClassB one class (parent) to both of their combined subclasses (children).
ClassA and ClassB both currently implement Serializable.
I am currently trying to make both inheritance chains inherit from ClassA, and then copy all functions and data members from ClassB into ClassA. This is tedious, and I think a terrible solution.
What would be the CORRECT way to solve this problem?
EDIT - some clarification
ClassA and ClassB essentially do the same thing (many calls to many Stored procs, through a series of many classes and method calls of course).
ClassA, however, makes the calls to half of the Stored Procs via a new service based (Jersey) architecture we implemented. I am essentially implementing the new service oriented functionality into "FamilyB" in the same way we it has already been done in "FamilyA". The problem is that each of these families are huge - many classes and long inheritance chains, making small changes has a butterfly effect on the inheritance chains.
If clarification is needed, please let me know.
The first answer that comes to mind is "In general, no".
In order for this to be reasonable, A and B should be special cases of some other thing -- although that is feasible, it would seem unlikely.
Besides that, I don't see any reason to combine any code (and a lot of reasons not to). Is there some reason you cannot simply have both of them extend X, and leave all their code where it is?
I don't think I have enough information for a clear picture yet, but will go with what I have so far.
If you implement a Class X that both Class A and Class B extend, that changes nothing about any subclasses or any use of either class or any subclass. That is certainly where I'd start.
public Class X implements Serializable {}
public Class A extends X implements Serializable
{
// retain all current code to start
}
public Class B extends X implements Serializable
{
// and here be all current code also
}
You say you are currently thinking of merging Class B into Class A; this sounds problematic; A and B share 'about half' of their code and both have a large inheritance tree below them - something that instantiates a Class A subclass could have its behavior changed by having A get some new functionality.
So instead I would move things slowly from A to X and from B to X. I would try to move things only if they had commonality between the A and B trees.
For instance, let's say you have method abc() in A and def() in B with the same functionality. You could move this functionality to X and call it anything you want - I would probably try to give it the name I thought best described its function, whether that came from A, B, or I made up a new one. Then abc() and def() could invoke this new function, and the code for these methods could be removed from both of them.
public class X implements Serializable
{
public void abcdef()
{
// common functionality, merged from A and B
}
}
public class A extends X implements Serializable
{
public function abc() { abcdef(); }
}
public class B extends X implements Serializable
{
public function edf() { abcdef(); }
}
One good thing about proceeding this way is that it is clear at each step what has been done. You could mark it well with comments and have it reviewed, and/or put it through tests to insure that functionality of both the refactored methods was complete and correct; this could be done after one, two, or more methods were refactored, depending on whether you have good setups for review and/or testing.
The only case where this might break is if, for some reason, you want the callers of methods in the two inheritance trees to change, but I don't have any reason (yet) to think that is necessary. Hopefully all the methods have at least reasonable names describing what they do and passing the parameters that need passing, and the refactoring at the top only affects the implementations, not the calls. It looks like a big enough job anyway, I'm hoping you don't have to change the calls as well as the functions.
My instinct is to create a new class that has objects of ClassA and ClassB as members, then use that as the base class for the things that you essentially want to derive from both ClassA and ClassB. For example:
class ClassAB
{
private ClassA a;
private ClassB b;
public void doSomething()
{
a.doSomething();
}
public void doSomethingElse()
{
b.doSomethingElse();
}
...
}
Sure, it's tedious, but it seems a lot easier and a lot less likely to lead to bugs than trying to rework ClassA and ClassB to make this possible. Does that work in this case?
Why don't you create a new class that ClassA and ClassB both extend and then start merging shared functionality up there.
Be sure that it actually makes sense to merge the code from ClassA and ClassB though.
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 .
I am facing a continuing problem distinguishing delegation, composition and aggregation from each other, and identifying the cases where it's the best to use one over the other.
I have consulted a Java OO Analysis and Design book, but my confusion still remains. The main explanation is this:
Delegation: When my object uses another object's functionality as is without changing it.
Composition: My object consists of other objects which in turn cannot exist after my object is destroyed-garbage collected.
Aggregation: My object consists of other objects which can live even after my object is destroyed.
Is it possible to have a few simple examples demonstrating each case, and the reasoning behind them? How else can these examples be demonstrated other than my object simply having a reference to another object(s)?
Delegation
public class A {
private B b = new B();
public void methodA() {
b.methodB();
}
}
When clients of A call methodA, class A delegates the call to B's methodB.
Rationale. Class A exposes behaviours that belong elsewhere. This can happen in single-inheritance languages where class A inherits from one class, but its clients need behaviours that are implemented in a different class. Further study.
Hybrid Delegation
public class A {
private B b = new B();
public void methodA() {
b.methodB( this );
}
}
The difference between delegation that involves simple forwarding and delegation that acts as a substitute for inheritance is that the callee must accept a parameter of the caller, exemplified as:
b.methodB( this );
Rationale. Allows class B instances to use functionality available from class A, just as class B would if it inherited from class A--but without inheritance. Further study.
Composition
public class A {
private B b = new B();
public A() {
}
}
Once no more references to a particular instance of class A exist, its instance of class B is destroyed.
Rationale. Allows classes to define behaviours and attributes in a modular fashion. Further study.
Aggregation
public class A {
private B b;
public A( B b ) {
this.b = b;
}
}
public class C {
private B b = new B();
public C() {
A a = new A( this.b );
}
}
Once there are no more references to a particular instance of class A, its instance of class B will not be destroyed. In this example, both A and C must be garbage collected before B will be destroyed.
Rationale. Allows instances to reuse objects. Further study.
Demonstration Without References
The names given to these simple patterns are defined by their referential relationships.
Your object would reference another object(s) in all three cases. The difference lies in behavior and / or lifecycle of referenced objects. Some examples:
Composition: House contains one or more rooms. Room's lifetime is controlled by House as Room will not exist without House.
Aggregation: Toy house built from blocks. You can disassemble it but blocks will remain.
Delegation: Your boss asked you to get him a coffee, you've had an intern do it for you instead. Delegation is not a type of association (like composition / aggregation are). The latter two have been discussed on Stack Overflow many times
In the comment you ask how the implementation would differ in each case, observing that in all cases we invoke methods on the releated objects. It's true that in each case we would have code such as
myRoom.doWork();
myBlock.doWork();
myMinion.doWork();
but the differences lie in the life-cycle and cardinality of the related objects.
For the Component, the Rooms come into existence when the House is created. So we might create them in the constructor of the House.
In the case of Association (I'll use Tyre and Car) Cars might add Tyres in their constructor, but later you may want to remove and change tyres. So you also have methods such as
removeTyre(FrontLeft)
addNewTyre(aTyre, BackRight)
And it's quite likely that the aTyre object came from a Factory - we didn't new it in any of the Car's methods.
In the case of Delegation, you might not even have a member variable to hold the delegate
resourcingPool().getIntern().getCoffee(SkinnyLatte, workstation 7);
the relationship between the objects lasts only as long as the intern is fetching the coffee. Then it returns to the resource pool.
Your book explains quite good so let me elaborate and provide you some examples.
delegation: When my object uses another object's functionality as is without changing it.
Sometime a class may logically need to be big. But big class is not a good coding pratice. Also sometime, some functionalities of a class may be implementable in more than one way and you may want to change that some time.
class FeatureHolder {
void feature() {
// Big implementation of the feature that you dont want to put in the class Big
}
}
class Big {
private FeatureHolder FH = new FeatureHolder();
void feature() {
// Delegate to FeatureHolder.
FH.feature();
}
//.. Other features
}
From the above example, Big.feature() call feature of FH as is without changing it. This way, the class Big does not need to contain the implementation of the feature (separation of labour). Also, feature() can implement differently by other class like "NewFeatureHolder" and Big may choose to use the new feature holder instead.
composition: My object consists of other objects which in turn cannot exist after my object is destryed-garbage collected.
aggregation: My object consists of other objects which can live even after my object is destroyed.
Technially, Composition is "part of" and Aggregation is "refer to" relationship. Your arms are part of you. If you no longer live, your arm will die too. Your cloth is not part of you but you have them; as you can guest, your cloth does not go with you.
In programming, some objects are part of another object and they have no logical meaning without it. For example, a button is composed into a window frame. If a frame is closed, the button has no reason to be around anymore (Composition). A button may have reference to a database (like to refreash data); when the button is eliminated, the database may still be around (Aggregation).
Sorry for my English, Hope this helps
1) Delegation: Man-driver-car example. A Man bought a car. But that man does not know to drive the car. So he will appoint a driver who knows driving a car. So the Man class wants to perform a transportation using car. But it does not have the interacting- functionality/compatibility with car. So he uses a class which has compatibility with car that is driver which is compatible with man class. Assuming that driver can understand what man says
2) Composition: Car simulation is a routine example. To make a car move, wheel rotates. Car class using wheel class rotate functinality as part of its move function, where as wheel is part of car.
3) Aggregation: Car and its colour. Car class object ferrari will have a colour class object red. But colour class object red can be there as individual class, when user search happens with a specification of red colour.
In a very simple sentence I can say:
Delegation is: delegate behaviour to other class when you do not want to change it. by change I mean during run time. for example you delegate driver to car class that driver wont change while driving.
Composition is: when you want to use behaviour of family of classes (one or more classes, that implements an interface) that you might change during run time. but you should consider these classes can not exist with out main classes, such as rooms of a hotel. If you remove hotel all rooms of hotel will not exist.
Aggregation is: same as composition but classes can exist without main class.