OOP multiple inheritance, polymorphism, aggregation and enumeration - oop

Was asked the following question,
Class C inherits from class B, class B inherits from class A
Would you call this
(1) Multiple inheritance
(2) Polymorphism
(3) Aggregation
(4) Enumeration
Now I was unsure of this, so I said enumeration. Correct answer is polymorphism. I can sort of see why, but I am having trouble explaining this from OOP principles.
Also, when it comes to OOP, what would 3 and 4 indicate?
Thanks.

Aggregation means, that an Object of class A contains (and makes use of) an object of class B.
Enumeration denotes just a data type which can be given a finite (usually small) set of named values (to group "things" together).
Multiple Inheritance would mean for a class to have more than one ancestor simultaneously (like Class a extends Class b, Class c, Class d).

Related

UML composition attributes not feature in the class?

I have a class A and it has data members of class B and class C which are composition relationships. As I am going to draw a composition relationship line from B to A and C to A, does this mean I cannot also include the data members within the class A "box" because the relationship is inferred from the composition relationship lines?
I ask because the data member variable names seem a good way to help understand the context and this cannot be represented if you omit the data members from the class A "box"??
I am not sure if there is a cast-iron rule in UML or whether I am free to choose. This is not for auto-generation of code- just human reading.
At least, in UML you can show a name of each property like a figure below.
According to UML specification, both representations of data members, visually depicted association/composition between two classes or in-class data member display) are equivalent. Here is an example (a little bit modified your case, to make it clearer):
Note that association end also show the scope and collection type (besides the name of course). col_B is defined ase private {ordered} collection (like array).
So, getting back to the formal side of UML spec... a, x, aa, col_b and m_c are all co called A's structural features (or properties). They can all be visually depicted using relationsips between the classes or inside the class itself. You can even show "int" data type as a class and link it using a composition!
Which way you will use is up to you, kind of matter of personal taste.
I always apply a simple rule - basic data types (int, boolean, date, string, etc) and their arrays are showed in the class itself, while the class and enumeration based properties are depicted by a relationship (example on the top).
As simple data types are clear and well known and does not have their own properties, I find it clear enough to show them in-class (diagram is simpler and smaller).
The complex data types (classes and enumerations) however typically have their own properties (data members, associations), even inheritances, and I want to make the class structure stand out on my diagarm.
You can use your own logic though.
In a class diagram you cannot model the same composition both showing the association and the attribute, because in the UML semantic that would mean your class has two composition :-)
If in your diagram you already have classes B and C, I suggest you opt for the association ("relationship lines") solution.
To better understand the context, you can put the roles on the association: this is equivalent to the name of your attributes.

How to model a domain object that can be of several types (in several states)?

Example : Having a human that can own 1 or more pets of different types (cat, dog, elephant, seal etc) .
I would think of making an aggregate that would have Human as root (that holds petCollection as reference to Pet) and another aggregate that would have Pet as root (with cat, dog, elephant, eagle as children for this aggregate) .
The problem is that each pet type can have different behaviour (example : a seal can swin() but it won't fly() / an eagle can fly() but it won't swim() ) . So a state or strategy pattern does not seem right . How can a human tell a pet object to run() if it doesn't know it's type ? Using the state/strategy pattern, the objects need to have similar behaviour . Doing an if/else (for the case of polymorphism to check the object type) check again , doesn't seem a proper design .
How should i design this domain or what patterns can help me here ?
Generally speaking, if something (only/always) is something, you should use Inheritance.
If something does something, you should use an Interface.
If something plays the role of something (e.g. a Legal Party plays the role of a Customer and/or a Supplier) you should use Composition.
So Seal inherits Animal and implements Swim, Bark
and
Dog inherits Animal and implements Run, Bark
If you want your animals to swim, then either iterate them checking if they implement Swim and then call swim(), or filter the collection prior to iterating through it to get the animals that implement Swim.
Aggregate roots and inheritance is not a very good idea typically.
You probably want to avoid one Aggregate to have a collection of other Aggregates.
The idea of the Aggregate (well, one of them) is that it represents transaction boundary, therefore there, ideally, should be no need in this structure.
It is normal, however, when one Aggregate has a collection of other Aggregates IDs.
I'm not sure there's anything really architecture or DDD related here. It's just basic OO (polymorphism).
If your starting point is a single pet and you want to trigger a behavior particular to its species, no secret - the caller has to know which subtype the pet is and reference the object with its real subtype, not Pet.
If your starting point is a Human and you want to call some behavior across all or part of its pets, you need to reason about something more abstract. If I understand the domain well, something like "an action that a human can tell an animal to perform".
Once you've found the proper name for that, create an abstract method with that name on Pet and have every subclass of Pet implement it in its own way. Then, thanks to polymorphism, you can tell a collection of pets to do it regardless of whether they are cats, dogs, or elephants.

difference between association and aggregation

I understand the difference between aggregation and composition but I am struggling a bit with association. My current understanding is that an association exists between classes when ‘they use each other’, for example, one object is passed to the other during a method call. See also:
http://www.codeproject.com/Articles/330447/Understanding-Association-Aggregation-and-Composit
Both objects exist independently and, in contrast to aggregation, no object is a container class of the other. Does this mean that both objects MUST have a copy of the other(s) (e.g. 1:m relationship) or how else is the association ‘stored’. Any feedback would be very much appreciated.
From the UML Superstructure 2.4.1:
An association declares that there can be links between instances of the associated types. A link is a tuple with one value for each end of the association, where each value is an instance of the type of the end. (UML Superstructure, Page 37)
Nothing more, nothing less. and very vague. Because of this, it is also very hard to understand. What I defined (In a course I teach) is a hierarchy of links from dependency to composition where:
Dependency from A to B means that A uses B but indirectly (say by receiving instances of it and forwarding them to other objects).
Association from A to B means that A uses B directly, (for example by calling methods)
Aggregation from A to B means that B is part of A (semantically) but B can be shared and if A is deleted, B is not deleted. Note that this says nothing about how the "is part" is implemented.
Composition from A to B is like Aggregation, where B cannot be shared and if A is deleted, all of its aggregates (Bs) are deleted also.
Aggregation is an Association relationship where the Association can be considered the containing class 'Owning' the contained class, and the lifetime of that relationship is not defined.
Association is an 'Has-A' relationship.
Example:-
public class Person
{
private final Name name;
private Address currentAddress;
//...
}
In this case, the Person Has-A name and Has-A Address, so there is an Association between Person and Name, and Person and Address.
An association describes a relationship between instances of one or more classes. In the words of the UML Reference Manual, "Associations are the glue that holds together a system."
Aggregation is a form of association in which there is a "whole-part" relationship. You may say that if a class Airplane has a class Engine then this forms a "whole-part" relationship.
Aggregation
Let's set the terms. The Aggregation is a metaterm in the UML standard, and means BOTH composition and shared aggregation, simply named shared. Too often it is named incorrectly "aggregation". It is BAD, for composition is an aggregation, too. As I understand, you meant you understand "shared aggregation and composition".
From UML standard:
Precise semantics of shared aggregation varies by application area and
modeler.
I haven't found a word about that aggregation supposed multiplicity, for example.
Association.
A definition from UML 3.4.1 standard:
An association describes a set of tuples whose values refer to typed
instances. An instance of an association is called a link. A link is a
tuple with one value for each end of the association, where each value
is an instance of the type of the end.
Aggregated relationship is a subclass of Association.
Association is based on relationship. IT is the glue for models.
But your feelings didn't lie - as the shared aggregation is not strictly defined, there is also NO any strictly defined boundary between Association and Aggregated association. Authors of tools and modellers have to set it themselves.
Association
It represents a relationship between two or more objects where all objects have their own lifecycle and there is no owner. The name of an association specifies the nature of relationship between objects. This is represented by a solid line.
Let’s take an example of relationship between Teacher and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers. But there is no ownership between the objects and both have their own lifecycle. Both can be created and deleted independently.
Aggregation
It is a specialized form of Association where all object have their own lifecycle but there is ownership. This represents “whole-part or a-part-of” relationship. This is represented by a hollow diamond followed by a line.
Let’s take an example of relationship between Department and Teacher. A Teacher may belongs to multiple departments. Hence Teacher is a part of multiple departments. But if we delete a Department, Teacher Object will not destroy.
It depends on the context.
Association: A man drives a car, focus on the caller and callee relationship.
Aggregation: A man has a car, focus on the owner and member relationship.
Composition: A man has a mouth, focus on the owner & member but the owner consists of members, it means that they shared the same life cycle.
Feels like I'm speaking Chinglish.
Association
Association is a relationship where all objects have their own life-cycle and there is no owner. Let’s take the example of Teacher and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers but there is no ownership between the objects and both have their own life-cycle. Both can create and delete independently.
Aggregation
the objects in Aggregation have their own life-cycle but there is ownership. Child object can not belong to another parent object. Let’s take an example of Department and teacher. A single teacher can not belongs to multiple departments, but if we delete the department teacher object will not destroy. We can think about the “has-a” relationship.
Composition
It is a strong type of Aggregation. Child object does not have their life-cycle and if parent object deletes all child object will also be deleted. Let’s take again an example of the relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room can not belongs to two different houses if we delete the house room will automatically delete.
An association between object types classifies relationships between objects of those types. For instance, the association Committee-has-ClubMember-as-chair, which is visualized as a connection line in the class diagram shown below, may classify the relationships FinanceCommittee-has-PeterMiller-as-chair, RecruitmentCommittee-has-SusanSmith-as-chair and AdvisoryCommittee-has-SarahAnderson-as-chair, where the objects PeterMiller, SusanSmith and SarahAnderson are of type ClubMember, and the objects FinanceCommittee, RecruitmentCommittee and AdvisoryCommittee are of type Committee.
See also my alternative CodeProject article.

Understanding when to use inheritance to allow one class to use instances of another

When creating classes, is there a rule for when to use inheritance and when to import a new class, without inheritance, into another?
Here’s an example:
I make a class called Person, and then create lots of Person objects.
I then create a child class called House. Using inheritance and properties, all my Person objects can now have a House.
I then create a child class called Car so all my Person objects now have Houses and Cars.
and so on… and so on….
I now have this sequence of classes:
NSObject < Person < House < Car < new Class < another new Class, etc.
With the above scenario, my logic (I'm an Objective-C beginner) tells me I have two different ways of producing the same outcome:
As explained above, or
Create each class without inheritance and then import it into Person as an ivar – for example, an instance of House now becomes a type, and that is then imported into a Person object using properties.
Please excuse my lack of terminology and understanding. If required, I can upload a code example but it’s more of a general question on when and when not to use inheritance.
This question is not specific to Objective-C: the guideline for when to use inheritance is the same for all object-oriented languages, and it is based on substitutability, summarized by the Liskov Substitution Principle:
if S is a subtype of T, then objects of type T may be replaced with objects of type S
In other words, use inheritance only when you can say "{derived} is a {base}>"; when you model a "{owner} has a {something}", use composition
Student is a Person -- Inheritance
Car is a vehicle -- Inheritance
Person has a House -- Composition (ivar or property)
Car has a(n) Engine -- Composition (ivar or property)

Table Per Subclass Vs Table Per concrete class in hibernate?

In most of the web application, i have seen one base class consisting common properties and number of subclasses extending base class . So my question here is which strategy we should go for among Table Per Subclass Vs Table Per concrete class. I personally feel we should go for table per subclass because in future if we want to introduce the common column we can do it at one place but in case of concrete class we have to do it in multiple tables. Right?
But yes if we want to fetch all deatils from all child tables i think Table per concrete class will be helpful Because we have to simply union the records from all tables but in case of Table per Sub class along with union we have to introduce the join with parent table which will be extra costlier .Right?
You might be interested in Section 2.12 "Inheritance Mapping Strategies" of the JPA 2.0 specification, as it sums up all possbible inheritance types as well as their advantages and drawbacks. Let me pull out just the most interesting fragments:
2.12.1 Single Table per Class Hierarchy Strategy
This mapping strategy provides good support for polymorphic
relationships between entities and for queries that range over the
class hierarchy. It has the drawback, however, that it requires that
the columns that correspond to state specific to the subclasses be
nullable.
2.12.3 Table per Concrete Class Strategy
This strategy has the following drawbacks:
- It provides poor support for polymorphic relationships.
- It typically requires that SQL UNION queries (or a separate SQL query per subclass) be issued for queries that are intended to range over the class hierarchy.
2.12.2 Joined Subclass Strategy
It has the drawback that it requires that one or more join operations
be performed to instantiate instances of a subclass. In deep class
hierarchies, this may lead to unacceptable performance. Queries that
range over the class hierarchy likewise require joins.
Also, if you're planning to be JPA-compatible, remember that the JPA-provider doesn't have to support TABLE_PER_CLASS strategy type.
I personally feel we should go for table per subclass because in
future if we want to introduce the common column we can do it at one
place but in case of concrete class we have to do it in multiple
tables.
True, but JOINED strategy also provides you the same feature and allows to specify common properties in one table.
Hope that helps!
The Object-Relational Impedance Mismatch
In Object Model, while creating object we may require to use inheritance i.e. Generalization as follows:
In Relational Model, the above Generalization(not association i.e. one-to-one or many-to-many) can achieve in Hibernate ORM with the following three inheritance mapping strategies:
Table Per Class i.e. for Hierarchy only one table
Table Per Concrete class i.e. One table for each concrete class not for super class
Table Per Subclass i.e. One table fore each class
In this strategy, we can map the whole hierarchy into single table, here we use one more discriminator column i.e. TYPE.
In this strategy, tables are created as per class but related by foreign key. So there are no duplicate columns.
In this strategy, tables are created as per class but related by foreign key. So there are no duplicate columns.
image source