Class Relationship

img src: https://creately.com/blog/diagrams/class-diagram-relationships/

   When we write an application, we wouldn't write just one class (right?). There should be multiple classes. Each will have their own unique task to do and sometime they need to interact with each other. This is called Class relationship, which define how classes are interact with each other.

  From UML definition, there are multiple type of class relationship. One of the reason is that it attempts to show the life time of each object in the relationship, but for simplicity I will categorize into just two types which are;

  • Inheritance
  • Composition
which have a completely different way of implementation. we will leave this object life time on later section so you won't be overflow with too much class relationship.

Inheritance

Inheritance (IS-A relationship) is a Relationship between two classes that allows one to inherit code from the other.

UML Diagram Representation

Below is an UML representation of inheritance relationship
for this Diagram we can say that
Dog, Bird, and Fish is an animal.

C# Implementation

Below is an implement template on how to implement inheritance relationship.

abstract class Animal
{
 //attribute and method that are common in all animal class
}
class Dog: Animal
{
 //attribute and method that are uniquely implement of Dog class
}
class Bird: Animal
{
 //attribute and method that are uniquely implement of Bird class
}
class Fish: Animal
{
 //attribute and method that are uniquely implement of Fish class
}

Composition

Composition (HAS-A Relationship) is a kind of relationship between two classes that allows one to contain the other

UML Diagram Representation

Below is an UML representation of composition relationship
for this Diagram we can say that
Car have an engine and a wheel.

C# Implementation

Below is an implement template on how to implement composition relationship.


class Car
{
 private Engine _myEngine;
 private Wheel _myWheel;

 public Car(Engine engine, Wheel wheel)
 {
  _myEngine = engine;
  _myWheel = wheel;
 }
}

class Wheel
{
}

class Engine
{
}

Deemarc Burakitbumrung

A software develper who graduated from Electronic and Communication Engineer. Have an interest in the field of programming and embedded system.

No comments:

Post a Comment