Friday, June 5, 2015

Day 3: CSharp - Class & Method - Inheritance & Polymorphism

Exercise 01:

Code:

Class Atomic Member

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FPT_Day03
{
    class AtomicMember
    {
        private int atoNum;
        private string atoSym;
        private string atoName;
        private float atoWeight;

        public AtomicMember(int pAtoNum, string pAtoSym, string pAtoName, float pAtoWeight)
        {
            AtoNum = pAtoNum;
            AtoSym = pAtoSym;
            AtoName = pAtoName;
            AtoWeight = pAtoWeight;
        }

        public int AtoNum
        {
            get
            {
                return atoNum;
            }

            set
            {
                atoNum = value;
            }
        }

        public string AtoSym
        {
            get
            {
                return atoSym;
            }

            set
            {
                atoSym = value;
            }
        }

        public string AtoName
        {
            get
            {
                return atoName;
            }

            set
            {
                atoName = value;
            }
        }

        public float AtoWeight
        {
            get
            {
                return atoWeight;
            }

            set
            {
                atoWeight = value;
            }
        }

        public override string ToString()
        {
            return "Number: " + AtoNum + " Symbol " + AtoSym + " Name " + AtoName  + " Weight " + AtoWeight;
        }
    }
}

Class AtomicManager

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FPT_Day03
{
    class AtomicManager
    {
        private List<object> atomList = new List<object>();

        public bool Accept()
        {
            int number;
            float weight;

            Console.WriteLine("Atomic Information");
            Console.WriteLine("===================");
            Console.Write("Enter atomic number: ");

            try
            {
                number = Int32.Parse(Console.ReadLine());
            }
            catch (Exception e)
            {
                Console.WriteLine("Please enter a number !\n");
                return false;
            }
            
            Console.Write("Enter symbol: ");
            string symbol = Console.ReadLine();
            Console.Write("Enter full name: ");
            string name = Console.ReadLine();
            Console.Write("Enter atomic weight: ");
            try
            {
                weight = float.Parse(Console.ReadLine());
            }catch (Exception e)
            {
                Console.WriteLine("Please enter a number !\n");
                return false;
            }
            
            AtomicMember s = new AtomicMember(number, symbol, name, weight);
            atomList.Add(s);
            return true;
        }

        public void Display()
        {
            foreach(object obj in atomList)
            {
                Console.WriteLine(obj);
            }
            Console.ReadLine();
        }

        public static void RunTheProgram()
        {
            int choice;
            AtomicManager am = new AtomicManager();
            do
            {

                Console.WriteLine("1 - Add atomic");
                Console.WriteLine("2 - Display");
                Console.Write("Your choice: ");
                choice = Int32.Parse(Console.ReadLine());

                switch (choice)
                {
                    case 1:
                        am.Accept();
                        break;
                    case 2:
                        am.Display();
                        break;
                }
            } while (choice != 0);
        }
    }
}

Class program

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FPT_Day03
{
    class Program
    {
        static void Main(string[] args)
        {
            AtomicManager.RunTheProgram();
            //Employee em01 = new Employee("Jimmy", "Hoang", "Vincom", 1, 2500);
            //Console.WriteLine(em01.ToString());
            //double money = em01.CaculateBonus(2.5);
            //Console.WriteLine(em01.FirstName + "'s salary after bonus: " + money);
            //Console.ReadLine();
        }
    }
}

Result


Exercise 02: 

Code:

Class Employee

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FPT_Day03
{
    class Employee
    {
        string firstName;
        string lastName;
        string address;
        long sin;
        double salary;

        public string FirstName
        {
            get
            {
                return firstName;
            }

            set
            {
                firstName = value;
            }
        }

        public string LastName
        {
            get
            {
                return lastName;
            }

            set
            {
                lastName = value;
            }
        }

        public string Address
        {
            get
            {
                return address;
            }

            set
            {
                address = value;
            }
        }

        public long Sin
        {
            get
            {
                return sin;
            }

            set
            {
                sin = value;
            }
        }

        public double Salary
        {
            get
            {
                return salary;
            }

            set
            {
                salary = value;
            }
        }

        public Employee(string pFirstName, string pLastName, string pAddress,long pSin, double pSalary)
        {
            firstName = pFirstName;
            lastName = pLastName;
            address = pAddress;
            sin = pSin;
            salary = pSalary;
        }

        public override string ToString()
        {
            return "First name: " + FirstName + "\nLast name: " + LastName + "\nAddress: " + Address +
                "\nSIN: " + Sin + "\nSalary " + Salary;
        }

        public double CaculateBonus(double percentage)
        {
            return percentage * Salary;
        }
    }
}

Class program

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FPT_Day03
{
    class Program
    {
        static void Main(string[] args)
        {
            //AtomicManager.RunTheProgram();
            Employee em01 = new Employee("Jimmy", "Hoang", "Vincom", 1, 2500);
            Console.WriteLine(em01.ToString());
            double money = em01.CaculateBonus(2.5);
            Console.WriteLine(em01.FirstName + "'s salary after bonus: " + money);
            Console.ReadLine();
        }
    }
}

Result


Summary

  • Trong OOP có 4 thứ quan trọng:
    • Abstraction ( Tính trừu tượng )
    • Encapsulation ( Tính đóng gói )
    • Polymorphism ( Tính đa hình)
    • Inheritance ( Tính kế thừa )

  1. Abstraction ( Tính trừu tượng )

    • Khi ta muốn tạo ra 1 class mà method trong đó chưa biết viết "body" của nó thế nào, thì ta dùng abstract
    • Example:
      • 
        
    • abstract class ShapesClass
      {
          abstract public int Area();
      }
    • 1 class mà derive từ abstract class thì phải implement tất cả các method từ abstract class đó ( trừ khi method đó dùng "virtual" )
    • Example:
    • class Square : ShapesClass
      {
          int side = 0;
      
          public Square(int n)
          {
              side = n;
          }
          // Area method is required to avoid 
          // a compile-time error. 
          public override int Area()
          {
              return side * side;
          }
      }
    • Abstract class không instantiate (khởi tạo) được.

2. Encapsulation ( Tính đóng gói )

  • Sử dụng các Access Modifier để giới hạn quyền truy cập
    • Public 
    • Private
    • Protected
    • Internal
    • Protected Internal

  3. Polymorphism ( Tính đa hình)

  • Sử dụng Virtual method
  • Virtual vs Abstract method
    • Abstract method ko có body, virtual ngược lại
    • Lớp con ( Derived class ) inherit lớp cha ( Base class ) thì phải implement & override hết nếu là abstract method. Virtual thì mình thích cái nào thì override cái đó.
  • Example: 
    • public class Shape
      {

      // Virtual method 
      public virtual void Draw()
          {
              Console.WriteLine("Performing base class drawing tasks");
          }
      }

      class Circle : Shape
      {
      public override void Draw()
          {
      // Code to draw a circle...
              Console.WriteLine("Drawing a circle");
      base.Draw();
          }
      }
      class Rectangle : Shape
      {
      public override void Draw()
          {
      // Code to draw a rectangle...
              Console.WriteLine("Drawing a rectangle");
      base.Draw();
          }
      }
      class Triangle : Shape
      {
      public override void Draw()
          {
      // Code to draw a triangle...
              Console.WriteLine("Drawing a triangle");
      base.Draw();
          }
      }

4. Inheritance ( Tính kế thừa )

  • lớp cha có gì thì lớp con có cái đó. Nhưng những gì lớp con có thì lớp cha có thể không có.
  • Example:
  • class <derived_class> : <base_class>
    {
       ...
    }

No comments:

Post a Comment