How to decide whether to use IS A or relate

public class B { public String getMe() { return "Some"; } } 

Suppose I have a class above, by what parameters should we decide what to use? Is this or is it related?

HAS - A

 public class A { public static void main(String args[]) { B b = new B(); System.out.println(b.getMe()); } } 

or

 public class A extends B { public static void main(String args[]) { A b = new A(); System.out.println(b.getMe()); } } 
+7
source share
3 answers

Depends on the logical relationship. It just needs to make sense.

Example:

Let's say you have animal classes.
So, you have these classes: animals, dogs, cats, leopards, furs, legs

Cat and Dog IS A Animal.
Leopard IS A Cat.
Animal HAS A Fur, Feet.

In a nutshell:

The IS relationship means that you inherit and extend the functionality of a base class.
HAS A means that the class uses a different class, so it has it as a member.

+16
source

There are 4 types of relationships:

  • Generalization (IS A) . This is implemented using inheritance, as you did above. It is used when class A has all the same functions of B, and you want to add some more functions. This way you just extend B and add new features.
  • Aggregation (HAS A) . This is slightly weaker than a generalization. You use this relation when object A owns objects B or consists of objects B (may be among other objects of other classes). The first type is called general aggregation, the second - composition. In aggregation and composition, there is usually an object that controls the life of another object (it creates it and destroys it as necessary).
  • Association . In an association, classes simply know about each other, so they are weaker than aggregation. Objects do not control each other.
  • Use . This is the weakest relation between the two classes, which means that one class can be displayed as a type in the method parameter or used inside the code.

    In your example, it should be aggregation (HAS A), if A has a field of type B. But if it just creates an instance of B that will be used inside the code and the object will be deleted from memory when the region ends, then this is not IS A, nor HAS A. It's just a usage relationship.

+10
source

In simple terms:

  • "represents" a representation of inheritance / extensions
  • β€œhas” represents delegation / association

eg:

  • A house is a building (inheritance).
  • The house has a door (s) (association).

Here is one of the best resources I have used to understand OOP: http://chortle.ccsu.edu/CS151/cs151java.html (parts 6 and 10)

+1
source

All Articles