Sunday, October 9

Composition Concept using C-sharp language source code


Composition is basically has a relationship and deals with the object creation in different classes. It is different from Inheritance. Object composition is a way to combine simple objects into more complex ones. Compositions are a critical building block of many basic data structures, including the tagged union, the linked list, and the binary tree, as well as the object used in object-oriented programming. Composited  objects are often referred to as having a "has a" relationship.



When, in a language, objects are typed, types can often be divided into composite and noncomposite types, and composition can be regarded as a relationship between types: an object of a composite type (e.g. car) "has an" object of a simpler type (e.g. wheel). This is the real-world example to understand the idea of composition. Another example which is a dong has four legs.in this example four legs are compsited in the dog class to make dog class prominent and well defined. Composition must be differentiated from subtyping. Subtyping raises the concept of inheritance e.g there are many classes and all the classes taking functionalties to of other classes.
In programming languages, composite objects are usually expressed by means of references from one object to another; depending on the language.Composition indicates that one class belongs to the other.  A polygon is made up of several points.  If the polygon is destroyed, so are the points.
The concept of composition is different from Inheritance and Polymorphism. you can achieve the concept of composition by making an object of one class into another. like this
is exactly like Aggregation except that the lifetime of the 'part' is controlled by the 'whole'. This control may be direct or transitive. That is, the 'whole' may take direct responsibility for creating or destroying the 'part', or it may accept an already created part, and later pass it on to some other whole that assumes responsibility for it.
If we were going to model a car, it would make sense to say that an engine is part-of a car. Within composition, the lifetime of the part (Engine) is managed by the whole (Car), in other words, when Car is destroyed, Engine is destroyed along with it. So in the programming point of view one must say this to drive a car t must have an engine. As entioned above that composition is basically has a relationship. so car class must have an object of Engine class to clear composition concept.
Composition is again specialize form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object dose not have their lifecycle and if parent object deletes all child object will also be deleted. Composition is not an inheritance and in composition one class may have an object of other class by making object in class you will be able to use functionality of that class by using its object within that class. Let’s take again an example of 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 house if we delete the house room will automatically delete. Let’s take another example relationship between Questions and options. Here is an example which is giving composition's concept an below this there is complete source using c-sharp language in this source code only composition is used in order to combine two objects of different classes.

class a
{
  b obj = new b(); //an Object of class b is created inside class a as a data member  
}
class b
{}
this is neither Inheritance nor Polymorphism. an object of class b can not bind itself with any method belongs toclass a. for example if class a is containing a method say Display method
class a
{
   b obj = new b();
   public void Display()
   {
       Console.WriteLine("Display Method of Class a");
   }
}
to call Display Method of class a you must have an object of class a in the main method. and an object of class b is not allowed to bind itself with this method. and every data member which we declare in class is implicitly Private and it is not accessed in the main program. Object Oriented Programming (OOP) is basically  comprised of four things.

  • Abstraction
  • Polymorphism
  • Inheritance
  • Encapsulation

/////////////////////////////////////////////////////////////////////////// Begins /////////////////////////////////////////////////////////////////////////////

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int choice, count = 0;
            Subject[] Sub = new Subject[5];
            for (int i = 0; i < Sub.Length; i++)
            {
                Sub[i] = new Subject();
            }
            Subject obj = new Subject();
            Console.Clear();
            Console.WriteLine("1 for Courses:");
            Console.WriteLine("2 for Students:");
            Console.WriteLine("3 for Display:");
            Console.WriteLine("4 for Exit:");
            Console.Write("Enter Your Choice:");
            choice = int.Parse(Console.ReadLine());
            do
            {
                if (choice == 1)
                {
                    obj.setSubjects(Sub);
                }
                else if (choice == 2)
                {
                   count =  obj.SetStudent(Sub);
                }
                else if (choice == 3)
                {
                    obj.Display(Sub,count);
                }
                else if (choice == 4)
                {
                    Environment.Exit(0);
                }
                else
                {
                    Console.WriteLine("\n\nInvalid Choice:\n\n");
                }
                Console.WriteLine("1 for Courses:");
                Console.WriteLine("2 for Students:");
                Console.WriteLine("3 for Display:");
                Console.WriteLine("4 for Exit:");
                Console.Write("Enter your Choice: ");
                choice = int.Parse(Console.ReadLine());
            }
            while (choice != 4);
        }
    }
    class Student
    {
        int id;
        string name;
        DateTime dob;
        int subcode;
        int subjectElected;
        public int StudentSubjectCode
        {
            set
            {
                subcode = value;
            }
            get
            {
                return subcode;
            }
        }
        public int StudentId
        {
            set
            {
                id = value;
            }
            get
            {
                return id;
            }
        }
        public string StudentName
        {
            set
            {
                name = value;
            }
            get
            {
                return name;
            }
        }
        public DateTime Studentdob
        {
            set
            {
                dob = value;
            }
            get
            {
                return dob;
            }
        }
        public int StudentElectedCourse
        {
            set
            {
                subjectElected = value;
            }
            get
            {
                return subjectElected;
            }
        }
    }
    class Subject
    {
        int subcode;
        string subtitle;
        Student[] student = new Student[4];
        public int SubjectId
        {
            set
            {
                subcode = value;
            }
            get
            {
                return subcode;
            }
        }
        public string SubTitle
        {
            set
            {
                subtitle = value;
            }
            get
            {
                return subtitle;    
            }
        }
        public void setSubjects(Subject[] Sub)
        {
            Console.Clear();
            for (int i = 0; i < Sub.Length; i++)
            {
                Sub[i] = new Subject();
                Console.Write("Enter Subject Code: ");
                int input = int.Parse(Console.ReadLine());
                Sub[i].SubjectId = input;
                Console.Write("Enter Subject Title:");
                string title = Console.ReadLine();
                Sub[i].SubTitle = title;
            }
            Console.Clear();
        }
        public void Display(Subject[] Sub,int count)
        {
            string courseTitle= " ";
            int flag = 0,j;
            for (int i = 0; i < Sub.Length; i++)
            {
               if (Sub[i].SubjectId == 0)
                {
                  flag =1;
                  break;
                }
            }
            if (flag == 1)
            {
                Console.Clear();
                Console.WriteLine("Sorry No Record Found:");
                Console.ReadLine();
            }
            else
            {
                Console.Clear();
                Console.WriteLine("Student Information\n\n\n");
                for (j = 0; j < count; j++ )
                {
                    for (int k = 0; k < Sub.Length; k++)
                    {
                        if (student[j].StudentElectedCourse == Sub[k].SubjectId)
                        {
                            courseTitle = Sub[k].subtitle;
                        }
                    }
                    Console.WriteLine("Student Id: " + student[j].StudentId);
                    Console.WriteLine("Student Name: " + student[j].StudentName);
                    Console.WriteLine("Student DOB: " + student[j].Studentdob.Year + "-" + student[j].Studentdob.Month + "-" + student[j].Studentdob.Day);


                    Console.WriteLine("Course Elected:");
                    Console.WriteLine("Course Id: " + student[j].StudentElectedCourse);
                    Console.WriteLine("Course Title: " + courseTitle);
                }
                Console.ReadLine();
            }
        }
        public int BindSubject(int choice, Subject[] sub)
        {
            int flag = 0;
                for (int i = 0; i < sub.Length; i++)
                {
                    if (choice == sub[i].subcode)
                    {
                        flag = 1;
                        break;
                    }
                }
            if (flag == 1)
            {
                return 1;
            }
            else
            {
                Console.Write("Invalid Code: ");
                return 0;
            }
        }
        public int SetStudent(Subject[] sub)
        {
            int choice, j= 0;
            char choiceData;
                for (int i = 0; i < student.Length; i++)
                {
                    student[i] = new Student();
                }
                Console.Clear();
                    do
                    {
                        Console.Write("Enter Id: ");
                        student[j].StudentId = int.Parse(Console.ReadLine());
                        Console.Write("Enter Student Name: ");
                        student[j].StudentName = Console.ReadLine();
                        Console.Write("Enter Date of Birth In this Format(YYYY-MM-DD): ");
                        string inputDob = Console.ReadLine();
                        student[j].Studentdob = Convert.ToDateTime(inputDob);
                        Console.Write("Enter Course Id: ");
                        do
                        {
                            choice = int.Parse(Console.ReadLine());
                        }
                        while (BindSubject(choice, sub) == 0);
                        student[j].StudentElectedCourse = choice;
                        j++;
                        Console.WriteLine("Do you want to Enter more Student?(y/n)");
                        Console.Write("Enter your Choice: ");
                        choiceData = char.Parse(Console.ReadLine());
                    }
                    while (choiceData != 'n');
                    return j;
        }
    }
}

/////////////////////////////////////////////////////////////////////////// Ends ///////////////////////////////////////////////////////////////////////////////

No comments:

Post a Comment