Object Oriented Programming in C# (Part2)

Pada Turtorial kedua ini akan dibahas beberapa topik yaitu:

  • Destroy Object
  • Overloading Method
  • Enkapsulasi Data dengan Property
  • Passing Value Type By Reference

Destroy Object

Karena C# menyediakan garbage collector, anda tidak perlu secara eksplisit men-destroy objek. Jika anda bekerja dengan unmanage resource (kode yang tidak di handle oleh CLR) maka anda tetap harus mendestroy objek secara manual. Adapun cara pendeklarasian destruktor pada C# sebagai berikut:

   1: ~MyClass( )
   2: {
   3:   // perintah disini
   4: }

Sintaks diatas akan diterjemahkan oleh compiler sebagai berikut

   1: protected override void Finalize()
   2:     {
   3:        try
   4:        {
   5:            // do work here
   6:        }
   7:        finally
   8:        {
   9:             base.Finalize();
  10:        }
  11:     }

Jika anda menggunakan managed code pada C# maka anda tidak diperbolehkan untuk mendestroy object secara langsung karena pada managed code, destroy object sudah diatur oleh komponen garbage collector pada CLR. Untuk men-destroy objek secepat mungkin setelah tidak diperlukan lagi anda dapat menggunakan interface Idisposable

   1: using System;
   2:     class Testing : Idisposable //menggunakan interface IDisposable
   3:     {
   4:        bool is_disposed = false;
   5:        protected virtual void Dispose( bool disposing )
   6:        {
   7:           if ( !is_disposed ) // hanya mendispose objek sekali!
   8:           {
   9:              if ( disposing )
  10:              {
  11:                 Console.WriteLine( "Not in destructor,
  12:                 OK to reference other objects" );
  13:              }
  14:              Console.WriteLine( "Disposing..." );
  15:           }
  16:           this.is_disposed = true;
  17:        }
  18:
  19:        public void Dispose( )
  20:        {
  21:           Dispose( true );
  22:           // memanggil Garbage Collector
  23:           GC.SuppressFinalize( this );
  24:        }
  25:
  26:        ~Testing( )
  27:        {
  28:           Dispose( false );
  29:           Console.WriteLine( "In destructor." );
  30:        }
  31:     }

Overloading Method

Pada C# anda dapat mendeklarasikan method atau konstruktor dengan nama yang sama pada sebuah class, tetapi parameter method tersebut harus berbeda bisa jumlah atau tipe datanya. Pada contoh dibawah ini akan ditunjukan bagaimana cara menggunakan overloading konstruktor

   1: public class Time
   2:     {
   3:         // private member variables
   4:         private int Year;
   5:         private int Month;
   6:         private int Date;
   7:         private int Hour;
   8:         private int Minute;
   9:         private int Second;
  10:
  11:         // public accessor methods
  12:         public void DisplayCurrentTime()
  13:         {
  14:             System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}",
  15:             Month, Date, Year, Hour, Minute, Second);
  16:         }
  17:
  18:         // constructors
  19:         public Time(System.DateTime dt)
  20:         {
  21:             Year = dt.Year;
  22:             Month = dt.Month;
  23:             Date = dt.Day;
  24:             Hour = dt.Hour;
  25:             Minute = dt.Minute;
  26:             Second = dt.Second;
  27:         }
  28:
  29:         public Time(string strTime) // overloading konstruktor
  30:         {
  31:             Console.WriteLine(strTime);
  32:         }
  33:
  34:         public Time(int Year, int Month, int Date,
  35:         int Hour, int Minute, int Second) // overloading konstruktor
  36:         {
  37:             this.Year = Year;
  38:             this.Month = Month;
  39:             this.Date = Date;
  40:             this.Hour = Hour;
  41:             this.Minute = Minute;
  42:             this.Second = Second;
  43:         }
  44:     }
  45:
  46:     class Tester
  47:     {
  48:         public void Run()
  49:         {
  50:             System.DateTime currentTime = System.DateTime.Now;
  51:             Time time1 = new Time(currentTime);
  52:             time1.DisplayCurrentTime();
  53:             Time time2 = new Time(2000, 11, 18, 11, 03, 30);
  54:             time2.DisplayCurrentTime();
  55:         }
  56:
  57:         static void Main()
  58:         {
  59:             Tester t = new Tester();
  60:             t.Run();
  61:         }
  62:     }

Selain konstruktor overloading juga bisa diterapkan pada method dalam suatu class yang sama, contoh penulisannya:

   1: void MyMethod(int p1);
   2: void MyMethod(int p1, int p2);    // beda banyak parameter
   3: void MyMethod(int p1, string s1); // beda tipe data

Enkapsulasi data dengan Property

Pada pemrograman berorientasi objek variabel dalam class biasanya diberi access modifier private, ini berarti hanya method dalam class tersebut yang dapat mengakses variabelnya. Yang menjadi pertanyaan bagaimana cara anda mengakses variabel bertipe private tersebut ?.

Anda bisa membuat public method set dan get untuk memberi dan mengambil nilai variabel tersebut, misal:

   1: // private member variables
   2:         private int Year;
   3:
   4:         public int getYear() //get method
   5:         {
   6:             return this.Year;
   7:         }
   8:
   9:         public void setYear(int Year) //set method
  10:         {
  11:             this.Year = Year;
  12:         }

Selain menggunakan cara tersebut diatas pada C# disediakan object property untuk memberi nilai dan mengambil nilai dari private variabel dalam suatu class. Penggunaan object property lebih memudahkan anda dalam penulisan kode dibandingkan harus membuat dua method set dan get untuk mengakses satu variabel private. Contoh penggunaan property dapat dilihat pada contoh kode dibawah ini.

   1: public class Time
   2:    {
   3:
   4:       // private member variables
   5:       private int year;
   6:       private int month;
   7:       private int date;
   8:       private int hour;
   9:       private int minute;
  10:       private int second;
  11:
  12:       // membuat property
  13:       public int Hour
  14:       {
  15:          get // mengambil nilai variable Hour
  16:          {
  17:             return hour;
  18:          }
  19:
  20:          set // memberi nilai variable Hour
  21:          {
  22:             hour = value;
  23:          }
  24:       }
  25:
  26:       // public  methods
  27:       public void DisplayCurrentTime( )
  28:       {
  29:          System.Console.WriteLine(
  30:          "Time: {0}/{1}/{2} {3}:{4}:{5}",
  31:          month, date, year, hour, minute, second );
  32:       }
  33:
  34:
  35:       // constructors
  36:       public Time( System.DateTime dt )
  37:       {
  38:          year = dt.Year;
  39:          month = dt.Month;
  40:          date = dt.Day;
  41:          hour = dt.Hour;
  42:          minute = dt.Minute;
  43:          second = dt.Second;
  44:       }
  45:
  46:
  47:    }
  48:     class Tester
  49:     {
  50:         public void Run()
  51:         {
  52:             System.DateTime currentTime = System.DateTime.Now;
  53:             Time t = new Time(currentTime);
  54:             t.DisplayCurrentTime();
  55:
  56:             // mengambil nilai variable Hour, get dijalankan
  57:             int theHour = t.Hour;
  58:
  59:             // menampilkan isi variable Hour
  60:             System.Console.WriteLine("Retrieved the hour: {0}",
  61:             theHour);
  62:
  63:             // increment
  64:             theHour++;
  65:
  66:             // memberi nilai variabel Hour dengan nilai baru
  67:             // set dijalankan
  68:             t.Hour = theHour;
  69:
  70:             // menampilkan isi variabel Hour setelah di-increament
  71:             System.Console.WriteLine("Updated the hour: {0}", t.Hour);
  72:         }
  73:
  74:
  75:         static void Main()
  76:         {
  77:             Tester t = new Tester();
  78:             t.Run();
  79:         }
  80:     }

Passing Value Type By Reference

Secara default di C# pengiriman nilai ke method menggunakan pass by value atau hanya mengirimkan nilai saja ke method seperti contoh dibawah ini

   1: public class Time
   2:     {
   3:         // private member variables
   4:         private int Year;
   5:         private int Month;
   6:         private int Date;
   7:         private int Hour;
   8:         private int Minute;
   9:         private int Second;
  10:
  11:
  12:         // public accessor methods
  13:         public void DisplayCurrentTime()
  14:         {
  15:             System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}",
  16:             Month, Date, Year, Hour, Minute, Second);
  17:         }
  18:
  19:         public void GetTime(int theHour, int theMinute, int theSecond)
  20:         {
  21:             theHour = Hour;
  22:             theMinute = Minute;
  23:             theSecond = Second;
  24:         }
  25:
  26:         // constructor
  27:         public Time(System.DateTime dt)
  28:         {
  29:
  30:             Year = dt.Year;
  31:             Month = dt.Month;
  32:             Date = dt.Day;
  33:             Hour = dt.Hour;
  34:             Minute = dt.Minute;
  35:             Second = dt.Second;
  36:         }
  37:
  38:
  39:     }
  40:
  41:     class Tester
  42:     {
  43:         public void Run()
  44:         {
  45:             System.DateTime currentTime = System.DateTime.Now;
  46:             Time t = new Time(currentTime);
  47:             t.DisplayCurrentTime();
  48:
  49:             int theHour = 0;
  50:             int theMinute = 0;
  51:             int theSecond = 0;
  52:             t.GetTime(theHour, theMinute, theSecond);
  53:             System.Console.WriteLine("Current time: {0}:{1}:{2}",
  54:             theHour, theMinute, theSecond);
  55:
  56:         }
  57:
  58:         static void Main()
  59:         {
  60:             Tester t = new Tester();
  61:             t.Run();
  62:         }
  63:     }

Jika kode diatas dijalankan hasilnya adalah

   1: 7/1/2008 12:22:19
   2: Current time: 0:0:0

Anda dapat melihat bahwa method t.GetTime(theHour, theMinute, theSecond); mencetak output 0:0:0 ini menandakan bahwa nilai yang dikirimkan ke method tersebut tidak dikembalikan ke variabel pemanggil methodnya (theHour, theMinute, theSecond). Jika anda ingin mengembalikan nilai ke variabel pemanggilnya maka anda harus menggunakan keyword ref. Penggunaan pass by ref pada method dapat dilihat pada contoh dibawah ini

   1: public class Time
   2:     {
   3:         // private member variables
   4:         private int Year;
   5:         private int Month;
   6:         private int Date;
   7:         private int Hour;
   8:         private int Minute;
   9:         private int Second;
  10:
  11:
  12:         // public accessor methods
  13:         public void DisplayCurrentTime()
  14:         {
  15:             System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}",
  16:             Month, Date, Year, Hour, Minute, Second);
  17:         }
  18:
  19:         // menggunakan references pada parameter
  20:         public void GetTime(
  21:            ref int theHour,
  22:            ref int theMinute,
  23:            ref int theSecond)
  24:         {
  25:             theHour = Hour;
  26:             theMinute = Minute;
  27:             theSecond = Second;
  28:         }
  29:         // constructor
  30:         public Time(System.DateTime dt)
  31:         {
  32:
  33:             Year = dt.Year;
  34:             Month = dt.Month;
  35:             Date = dt.Day;
  36:             Hour = dt.Hour;
  37:             Minute = dt.Minute;
  38:             Second = dt.Second;
  39:         }
  40:
  41:
  42:     }
  43:
  44:     class Tester
  45:     {
  46:         public void Run()
  47:         {
  48:             System.DateTime currentTime = System.DateTime.Now;
  49:             Time t = new Time(currentTime);
  50:             t.DisplayCurrentTime();
  51:
  52:             int theHour = 0;
  53:             int theMinute = 0;
  54:             int theSecond = 0;
  55:
  56:             // pass integer by reference
  57:             t.GetTime(ref theHour, ref theMinute, ref theSecond);
  58:
  59:             System.Console.WriteLine("Current time: {0}:{1}:{2}",
  60:             theHour, theMinute, theSecond);
  61:
  62:         }
  63:
  64:         static void Main()
  65:         {
  66:             Tester t = new Tester();
  67:             t.Run();
  68:         }
  69:     }

Jika program diatas dijalankan maka hasilnya

   1: 7/1/2008 12:25:41
   2: Current time: 12:25:41

bersambung ke Object Oriented Programming in C# (Part3)

pustaka: “Learning C# 2005”, Jesse Liberty, Brian MacDonald, O’Reilly 2006

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s