Monday 26 September 2016

16. Classes C# (Basic/Dasar)

Ketika kita mendefinisikan class, make kita seperti mendefinisikan sebuah blueprint dari tipe data. Class tidak mendefinisikan aktual data, di dalam class terdapat member dari class seperti variabel dan methods.

Mendefinisikan Class

Class dapat didefinisikan dengan keyword class diikuti dengan nama class, sedangkan body class ditandai dengan curly braces {}.

<access specifier> class  class_name
{
   // member variables
   <access specifier> <data type> variable1;
   <access specifier> <data type> variable2;
   ...
   <access specifier> <data type> variableN;
   // member methods
   <access specifier> <return type> method1(parameter_list)
   {
      // method body
   }
   <access specifier> <return type> method2(parameter_list)
   {
      // method body
   }
   ...
   <access specifier> <return type> methodN(parameter_list)
   {
      // method body
   }
}

  • <access specifier> : Merupakan aturan akses untuk class yang lain, jika class didefinisikan tanpa access specifier maka secara default class tersebut akan mempunyai internal access specifier. Sedangkan default access specifier untuk member class adalah private.
  • <data type>, <return type> : Merupakan hal yang sama yang merupakan tipe data yang dipakai misalnya int, double dll.
  • Untuk mengakses member dari class kita menggunakan dot (.)

using System;
namespace BoxApplication
{
    class Box
    {
       public double length;   // Length of a box
       public double breadth;  // Breadth of a box
       public double height;   // Height of a box
    }
    class Boxtester
    {
        static void Main(string[] args)
        {
            Box Box1 = new Box();   // Declare Box1 of type Box
            Box Box2 = new Box();   // Declare Box2 of type Box
            double volume = 0.0;    // Store the volume of a box here

            // box 1 specification
            Box1.height = 5.0;
            Box1.length = 6.0;
            Box1.breadth = 7.0;

            // box 2 specification
            Box2.height = 10.0;
            Box2.length = 12.0;
            Box2.breadth = 13.0;
           
            // volume of box 1
            volume = Box1.height * Box1.length * Box1.breadth;
            Console.WriteLine("Volume of Box1 : {0}",  volume);

            // volume of box 2
            volume = Box2.height * Box2.length * Box2.breadth;
            Console.WriteLine("Volume of Box2 : {0}", volume);
            Console.ReadKey();
        }
    }
}

Ketika program dijalankan akan memberikan hasil sebagai berikut:

Volume of Box1 : 210
Volume of Box2 : 1560

Member Function and Encapsulation

Member function adalah adalah definisi dalam prototype class, function didefinisikan di dalam class mempunyai akses pada semua member dari class.

Member Variable adalah properti dari class, secara default akan mempunyai hak akses private. Jika variable akan diakses dari class yang lain maka harus didefinisikan sebagai public, protected, internal sesuai dengan desain dari program.

Berikut adalah contoh program untuk mengilustrasikan akses dari member class:

using System;
namespace BoxApplication
{
   class Box
   {
      private double length;   // Length of a box
      private double breadth;  // Breadth of a box
      private double height;   // Height of a box
      public void setLength( double len )
      {
         length = len;
      }
      
      public void setBreadth( double bre )
      {
         breadth = bre;
      }
      
      public void setHeight( double hei )
      {
         height = hei;
      }
      public double getVolume()
      {
         return length * breadth * height;
      }
   }
   class Boxtester
   {
      static void Main(string[] args)
      {
         Box Box1 = new Box();   // Declare Box1 of type Box
         Box Box2 = new Box();
         double volume;
         
         // Declare Box2 of type Box
         // box 1 specification
         Box1.setLength(6.0);
         Box1.setBreadth(7.0);
         Box1.setHeight(5.0);
         
         // box 2 specification
         Box2.setLength(12.0);
         Box2.setBreadth(13.0);
         Box2.setHeight(10.0);
         
         // volume of box 1
         volume = Box1.getVolume();
         Console.WriteLine("Volume of Box1 : {0}" ,volume);
         
         // volume of box 2
         volume = Box2.getVolume();
         Console.WriteLine("Volume of Box2 : {0}", volume);
         
         Console.ReadKey();
      }
   }
}

Hasil keluaran program akan sebagai berikut:

Volume of Box1 : 210
Volume of Box2 : 1560

C# Constructor

Constructor adalah spesial member dari class yang akan dieksekusi ketika object class dibuat. Sebuah constructor mempunyai nama seperti class tetapi tidak memiliki nilai kembalian dan selalu public karena akan diakses dari luar class.

Program berikut ini mengilustrasikan konsep constructor pada class:

using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // Length of a line
      public Line()
      {
         Console.WriteLine("Object is being created");
      }

      public void setLength( double len )
      {
         length = len;
      }
      
      public double getLength()
      {
         return length;
      }

      static void Main(string[] args)
      {
         Line line = new Line();    
         
         // set line length
         line.setLength(6.0);
         Console.WriteLine("Length of line : {0}", line.getLength());
         Console.ReadKey();
      }
   }
}

Setelah program dijalankan akan memberikan hasil sebagai berikut:

Object is being created
Length of line : 6

Default constructor tidak memiliki parameter, tetapi jika kita membutuhkan parameter masukan pada constructor kita bisa membuat constructor dengan variabel. Dengan teknik semacam ini kita bisa menginisialisasi member dalam object class ketika object dibuat.

Berikut adalah contoh program untuk mengilustasikan parameterized constructor:

using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // Length of a line
      public Line(double len)  //Parameterized constructor
      {
         Console.WriteLine("Object is being created, length = {0}", len);
         length = len;
      }

      public void setLength( double len )
      {
         length = len;
      }
      public double getLength()
      {
         return length;
      }

      static void Main(string[] args)
      {
         Line line = new Line(10.0);
         Console.WriteLine("Length of line : {0}", line.getLength()); 
         
         // set line length
         line.setLength(6.0);
         Console.WriteLine("Length of line : {0}", line.getLength()); 
         Console.ReadKey();
      }
   }
}

Setelah program dijalankan akan memberikan keluaran sebagai berikut:

Object is being created, length = 10
Length of line : 10
Length of line : 6

C# Destructor

Destructor pada dasarnya sama dengan constructor yang memberdakan adalah, destructor tidak mempunyai parameter atau dengan kata lain tidak dapat dicustom seperti constructor. Destructor dipanggil ketika object di destroy. Untuk mendefinisikan destructor kita menggunakan prefix tilde (~) sebelum nama destructor.

Destructor akan sangat bermanfaat untuk melepaskan memory yang terpakai ketika kita keluar dari program. Destructor tidak bisa di diturunkan (inheritance) dan overloaded.

Berikut adalah contoh program untuk mengilustrasikan penggunaan destructor:

using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // Length of a line
      public Line()  // constructor
      {
         Console.WriteLine("Object is being created");
      }
      ~Line() //destructor
      {
         Console.WriteLine("Object is being deleted");
      }

      public void setLength( double len )
      {
         length = len;
      }
      
      public double getLength()
      {
         return length;
      }

      static void Main(string[] args)
      {
         Line line = new Line();
         
         // set line length
         line.setLength(6.0);
         Console.WriteLine("Length of line : {0}", line.getLength());           
      }
   }
}

Setelah program dijalankan akan memberikan hasil sebagai berikut:

Object is being created
Length of line : 6
Object is being deleted

Static Member dalam C#

Kita juga bisa mendefinisikan class member sebagai static dengan menggunakan keyword static. Ketika kita mendefinisikan class member sebagai static maka berapa kalipun object class dibuat maka static member tetap hanya ada satu.

Static member hanya akan ada satu meskipun object class dibuat secara berulang ulang, untuk mengakses static member kita tidak harus membuat instance object dari class.

Program berikut akan mengilustrasikan static variabel:

using System;
namespace StaticVarApplication
{
   class StaticVar
   {
      public static int num;
      public void count()
      {
         num++;
      }
      public int getNum()
      {
         return num;
      }
   }
   class StaticTester
   {
      static void Main(string[] args)
      {
         StaticVar s1 = new StaticVar();
         StaticVar s2 = new StaticVar();
         s1.count();
         s1.count();
         s1.count();
         s2.count();
         s2.count();
         s2.count();
         Console.WriteLine("Variable num for s1: {0}", s1.getNum());
         Console.WriteLine("Variable num for s2: {0}", s2.getNum());
         Console.ReadKey();
      }
   }
}

Setelah program dijalankan akan memberikan output sebagai berikut:

Variable num for s1: 6
Variable num for s2: 6

kita juga bisa mendefinisikan method atau function sebagai static member, program berikut mengilustrasikan static method pada class:

using System;
namespace StaticVarApplication
{
   class StaticVar
   {
      public static int num;
      public void count()
      {
         num++;
      }
      public static int getNum()
      {
         return num;
      }
   }
   class StaticTester
   {
      static void Main(string[] args)
      {
         StaticVar s = new StaticVar();
         s.count();
         s.count();
         s.count();
         Console.WriteLine("Variable num: {0}", StaticVar.getNum());
         Console.ReadKey();
      }
   }
}

Keluaran program setelah aplikasi dijalankan adalah sebagai berikut:

Variable num: 3

Ok guys, sampai ketemu di tutorial selanjutnya ya Inheritance.

No comments:

Post a Comment