Monday 1 October 2012

What Are The Relationship Types in Java?

Java programs are comprised of a set of interacting objects, and Java derives its power from the relationships between different objects. Relationships allow a programmer to define complicated objects by building them out of a simpler series of objects, thus easing the process of debugging and creating code that can be reused for multiple purposes.

Based on reusing the data members from one class to another class in JAVA we have three types of relationships. They are is-a relationship, has-a relationship and uses-a relationship.

Is-a relationship is one in which data members of one class is obtained into another class
through the concept of inheritance.
For example, if you are writing an architecture program, you might create a parent class "Fruit" and child classes "Apple," "Banana" and "Mango." Each of the child classes inherits variables and methods from the parent class. In this example, they might inherit variables such as "hasSeeds" or "color," and methods such as "getCost" because fruit can be defined by the presences of seeds, its color and its cost. Each child class might also have its own variables or methods that are not present in the other classes. The apple class, for example, might have "numSeeds" or "stemLength" variables.

Has-a relationship is one in which an object of one class is created as a data member in
another class. For example, the class "Orchard" may contain "Tree" objects that define the trees that is present in the orchard. In this case, you would say that the orchard "Has A" tree. The "Tree" class may also have a compositional relationship with other objects, such as "Fruit" or "Flower" objects.
Uses-a relationship is one in which a method of one class is using an object of another class. Typically the relationship between the two classes is short-term. In Java, the dependence relationship can be best seen when an object is passed as a parameter in a method call. Once the method has finished executing, the object is no longer needed and is discarded.

No comments:

Post a Comment